5

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?

PM4
  • 624
  • 1
  • 5
  • 18

1 Answers1

7

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.

Mike M.
  • 38,532
  • 8
  • 99
  • 95
  • 3
    This works but some times it kills the app. Happens on Android 10 devices. – krisDrOid Oct 26 '20 at 20:42
  • 1
    @krisDrOid, Any work around to stop closing app on reverting the permission? – shobhan Aug 03 '22 at 08:10
  • Don't know why this didn't occur to me earlier, but the comments on [this question concerning app icons](https://stackoverflow.com/q/68576022) might be relevant to the issue noted in comments here. There, they start out with the relevant component set as `android:enabled="false"` in the manifest. They then use `COMPONENT_ENABLED_STATE_ENABLED` to turn it on, but to disable it they use `_DEFAULT`, not `_DISABLED`, which doesn't kill the app somehow. I never did look to see how that actually works internally, so I have absolutely no idea if it's even applicable here. Just thought I'd mention it. – Mike M. Mar 18 '23 at 20:58