Home > DeveloperSection > Forums > Under what condition could the code sample below crash your application? How would you modify the code to avoid this potential problem?
Anurag Sharma
Anurag Sharma

Total Post:40

Points:280
Posted on    August-04-2015 11:19 PM

 Android Android  Android Intent 
Ratings:


 1 Reply(s)
 756  View(s)
Rate this:
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
    sendIntent.setType(HTTP.PLAIN_TEXT_TYPE); // "text/plain" MIME type
    startActivity(sendIntent);


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    August-05-2015 9:18 AM

An implicit intent specifies an action that can invoke any app on the device able to perform the action. Using an implicit intent is useful when your app cannot perform the action, but other apps probably can. If there is more than one application registered that can handle this request, the user will be prompted to select which one to use.

However, it is possible that there are no applications that can handle your intent. In this case, your application will crash when you invoke startActivity(). To avoid this, before calling startActivity() you should first verify that there is at least one application registered in the system that can handle the intent. To do this use resolveActivity() on your intent object:

    // Verify that there are applications registered to handle this intent
    // (resolveActivity returns null if none are registered)
    if (sendIntent.resolveActivity(getPackageManager()) != null) {
        startActivity(sendIntent);
    } 


Don't want to miss updates? Please click the below button!

Follow MindStick