androidandroid-intentsmsandroid-4.4-kitkattelephony

Automatically revert to previous default SMS app


I have an app that requires temporary access to the device's SMS. In KitKat and above, this access is only granted to the default SMS app, so I'm using:

Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
startActivity(intent);

This brings up a dialog asking the user if they let my app become the default SMS app. So far so good. Problem is, once my app completes its operation, I have to ask the user again, if they want to restore their previous app as their default SMS app.

I'd like a way to avoid the second dialog, perhaps by having my app tell the Android OS that it no longer wishes to be the default SMS app, so that the previous app can automatically take over again. I know Android supports this, because if I uninstall my app while it is the default SMS app, Android will revert to the previous one automatically, with no need for user input. Any way to replicate this behaviour of ceding control without uninstalling?


Solution

  • To be eligible to be the default messaging app, your app has to have certain active components registered in the manifest. Disabling any one of them will make your app ineligible, and the system should automatically revert the default. We can use the PackageManager#setComponentEnabledSetting() method to disable a manifest-registered component.

    For example, if the Receiver you have registered for the SMS_DELIVER action is named SmsReceiver:

    getPackageManager()
        .setComponentEnabledSetting(new ComponentName(this, SmsReceiver.class),
                                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                                    PackageManager.DONT_KILL_APP);
    

    Obviously, before your app could be set as the default again, you would need to re-enable that component, which you can do by calling the above method with PackageManager.COMPONENT_ENABLED_STATE_ENABLED as the second argument.