androidflutterbroadcastreceiverandroid-package-managersstart-activity

How can I programmatically start a Flutter application from a BroadcastReceiver?


The purpose of my implementation of a BroadcastReceiver is to be able to start a closed Flutter application when an incoming or outgoing call ends. The Flutter application has native Android code in order to configure a service that allows the tracking of the phone state in the background. The BroadcastReceiver works and calls the appropriate functions when the phone state changes. For example, the onReceive method calls the onIncomingCallEnded function when an incoming call is ended. This function is then passed the Context object of the onReceive method which is used to create an intent, by using PackageManager, as described in this post. That intent should then start the Flutter application if it's closed.

    protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end)
    {
        Log.i("CallObserver", "We finished a call");

        Intent i = ctx.getPackageManager().getLaunchIntentForPackage("com.example.flutter_call_app_java");
        if(i != null) {
            Log.i("CallObserver","intent is not null");
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //Used to start an Activity outside of an Activity Context.
            ctx.startActivity(i);
        }
        else {
            Log.e("CallObserver","Couldn't start app");
        }
    }

When the onIncomingCallEnded function is called, the log shows that the intent is not null, but the Flutter application does not start. There are no errors present in Logcat. I have referred to a post by James Gardiner as well as a separate post by nub and although their goals are related to mine, the solutions to their questions don't seem to work for my use case (I have tested their solutions). I have also implemented a remark by Ramakrishna Joshi regarding the placement of the package name in the AndroidManifest in order to check if a package is installed on user's device. I'm using an Android emulator for Android API 30, in Android Studio Arctic Fox | 2020.3.1 Patch 4 , on a Windows 10 desktop.


Solution

  • The observation by David Wasser turned out to be correct. Everything works as it's intended when using API 28 and below but fails for API 29 and above due to restrictions on starting activities from the background. The display of notifications seem to be an appropriate compromise for my use case.