Incorrect way to launch SMS intent in Android

In my Android app, I use the following code to start the messaging app and populate the default text for the text message:

Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("sms:"+USERS_PHONE_NUMBER)); intent.putExtra("sms_body", "DUMMY TEXT"); startActivity(intent); 

This works in most cases. But unfortunately, on some devices the following error message appears:

 android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=sms:+XXXXXXXXXX (has extras) } at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1510) at android.app.Instrumentation.execStartActivity(Instrumentation.java:1384) at android.app.Activity.startActivityForResult(Activity.java:3131) at android.app.Activity.startActivity(Activity.java:3237) 

Obviously, the intention that I created cannot be processed.

  • Is there any error in my SMS intent code?
  • How can I prevent the application from crashing if the intention cannot be fulfilled?

Should I use PackageManager.queryIntentActivities () or is there any other way to solve this problem?

Thanks in advance!

+4
source share
3 answers

I have not tried this intent on purpose, but the easiest way would probably be to add a try and catch block

 try { startActivity(intent); } catch (ActivityNotFoundException e) { // Display some sort of error message here. } 

Since you cannot count on the fact that there is a Messages application on a specific Android device (some tablets, for example, do not have telephony services), you should be prepared.

It is good practice when you start external actions to avoid crashes in your application.

+12
source

Here is the code that will open the SMS activity, pre-filled with the phone number to which you need to send SMS. This works great on both the emulator and the device.

 Intent smsIntent = new Intent(Intent.ACTION_SENDTO); smsIntent.addCategory(Intent.CATEGORY_DEFAULT); smsIntent.setType("vnd.android-dir/mms-sms"); smsIntent.setData(Uri.parse("sms:" + phoneNumber); 
+2
source

Here is the way I use to safely open actions on Android and give the user some feedback if no activity is found.

 public static void safeOpenActivityIntent(Context context, Intent activityIntent) { // Verify that the intent will resolve to an activity if (activityIntent.resolveActivity(context.getPackageManager()) != null) { context.startActivity(activityIntent); } else { Toast.makeText(context, "app not available", Toast.LENGTH_LONG).show(); } } 

(I think I got it from one of Google’s developer videos on YouTube, but now I can’t find the video ...)

0
source

Source: https://habr.com/ru/post/1399100/


All Articles