android-intentsmstelephony

Android: add resolveActivity() as well as default app's setPackage() code?


For API 19+, having a default app became available, so a null check for the default app could then occur. My question is, once an Intent is set to the default app using setPackage(), is it still worthwhile to use a resolveActivity() null check on the Intent or is that redundant or overkill?

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

    String defaultSMSPackageName = Telephony.Sms.getDefaultSmsPackage(this);
    final Intent smsIntent = new Intent(Intent.ACTION_SENDTO);

    if (defaultSMSPackageName != null) {

        smsIntent.setPackage(defaultSMSPackageName);
        **if (smsIntent.resolveActivity(getPackageManager()) != null)** {
              startActivity(smsIntent);
              finish();
        }
    }    
}

or just use this:

    ...  

    if (defaultSMSPackageName != null) {

        smsIntent.setPackage(defaultSMSPackageName);
        startActivity(smsIntent);
        finish();
        
    }  

      

Solution

  • For a situation like this, I would never use resolveActivity(). It doesn't solve all problems (e.g., SecurityException when trying to start the other activity). I would just wrap the startActivity() call in try/catch.

    Something like resolveActivity() can be useful in places where you need to know that the other activity is unavailable before you try starting it. For example, perhaps you want to disable some button based on whether the other activity is available. Still, you should wrap the startActivity() call in try/catch. And bear in mind that on Android 11+ you will need to deal with package visibility rules for resolveActivity() to work.