Using Intent.createChooser and getting error: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag

Tags: , , , ,



I want to open the share via option from the service class. It is working fine in Android 7, but in 8+ OS it starts showing

android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

I have also included this flag to my Intent, but it’s still showing the same error.

Is there any other way to open share via option from the service class?

                    Intent i = new Intent(Intent.ACTION_SEND);
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    i.putExtra(Intent.EXTRA_STREAM, rasta);  //rasta -> Uri obj
                    i.setType("image/*");
                    getApplicationContext().startService(Intent.createChooser(i,"Share karna..."));

Answer

Intent.createChooser creates an Intent, so you need to set the FLAG_ACTIVITY_NEW_TASK flag on that intent, e.g.,

                    Intent i = new Intent(Intent.ACTION_SEND);
                    i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    i.putExtra(Intent.EXTRA_STREAM, rasta);  //rasta -> Uri obj
                    i.setType("image/*");
                    Intent chooserIntent = Intent.createChooser(i,"Share karna...");
                    chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    getApplicationContext().startActivity(chooserIntent);

You were also calling startService instead of startActivity – make sure to correct that as well.



Source: stackoverflow