Is it possible to launch an Activity or raise an I

2019-08-20 17:36发布

问题:

I have custom app class

public class MyApp extends Application {

    public static Context application_context;

 @Override
    public void onCreate() {
        super.onCreate();
application_context=getApplicationContext();
    }

    public static void startShareIntent() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, "some text");

        shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");
        application_context.startActivity(Intent.createChooser(shareIntent, 
                                                                  "Share with"));
    }
}

and when I call this method I receive this error message

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

YES it is that what really want but why I can not do it ?

回答1:

When you call Intent.createChooser(), this returns a new ACTION_CHOOSER Intent which does NOT have the FLAG_ACTIVITY_NEW_TASK set. That's why you are getting this error. Maybe you want something like this:

public static void startShareIntent() {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(Intent.EXTRA_TEXT, "some text");

    shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    shareIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");
    Intent chooserIntent = Intent.createChooser(shareIntent, "Share with");
    chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    application_context.startActivity(ChooserIntent);
}