简体   繁体   中英

Is it possible to launch an Activity or raise an Intent from static method in Application class?

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 ?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM