androidandroid-intentserviceshareintentservice

Android share intent from intentservice


I want to share multiple images from my app to other apps. On Android's developer page, I found:

Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, SavedImages);
        shareIntent.setType("image/*");
        startActivity(Intent.createChooser(shareIntent, "Share images to.."));

How can I use this code from an intentservice? When using the sample code from an intentservice, my app crashes with logcat error:

Calling startActivity from outside of an Activity context requires the flag FLAG_ACTIVITY_NEW_TASK

So I added

shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

but I still get the same error and my app crashes.

How can I use the share intent from an intentservice?


Solution

  • This line of code

    startActivity(Intent.createChooser(shareIntent, "Share images to.."));
    

    That means you create an intent object which is used to start a dialog activity for user to choose which activity to handle your shareIntent. So, in this case the intent to show chooser dialog activity need the flag FLAG_ACTIVITY_NEW_TASK
    You can try:

    Intent chooserIntent = Intent.createChooser(shareIntent, "Share images to..");
    chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(chooserIntent);