从Activity上下文外部调用startActivity()需要FLAG_ACTIVITY_NEW_TASK标志

时间:2018-01-11 08:16:06

标签: android android-intent android-service android-input-method

我在Android中创建了表情符号键盘,但我可以在键盘视图中添加共享此应用按钮。

这是我的点击共享方法。

public void shareapp() {
    String shareText = getResources().getString(R.string.share_text);
    Intent sendIntent = new Intent();
    sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, shareText + "https://play.google.com/store/apps/details?id=" + getPackageName());
    sendIntent.setType("text/plain");
    Intent chooseIntent = Intent.createChooser(sendIntent, "Share this via");
    getApplication().getApplicationContext().startActivity(chooseIntent);
}

但点击共享应用按钮时会发生错误 见错误:

01-11 13:36:03.728 8795-8795/com.example.napturalistamoji E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.napturalistamoji, PID: 8795
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
    at android.app.ContextImpl.startActivity(ContextImpl.java:747)
    at android.app.ContextImpl.startActivity(ContextImpl.java:734)
    at android.content.ContextWrapper.startActivity(ContextWrapper.java:345)
    at com.example.napturalistamoji.service.KeyboardService.shareapp(KeyboardService.java:685)
    at com.example.napturalistamoji.service.KeyboardService.onClick(KeyboardService.java:566)
    at android.view.View.performClick(View.java:5721)
    at android.view.View$PerformClick.run(View.java:22620)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:7331)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

任何人都可以帮我解决问题吗?

1 个答案:

答案 0 :(得分:1)

在开始像这样的活动

时,你需要为你的意图设置标志
Intent chooseIntent = Intent.createChooser(sendIntent, "Share this via");
chooseIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().getApplicationContext().startActivity(chooseIntent);

您在错误的意图上设置了标记。