如何解决android.util.AndroidRuntimeException:从活动标志外部调用 startActivity()
... 来自 Activity 上下文之外的需要 FLAG_ACTIVITY_NEW_TASK 标志。这真的是你想要的吗?
我正在尝试分享我在图像视图中的图像
shareButton.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
shareImage(getApplicationContext(),resID);
}
});
}
public static void shareImage(Context context,Integer resource_id) {
Bitmap b = BitmapFactory.decodeResource(context.getResources(),resource_id);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG,100,bytes);
String path = MediaStore.Images.Media.insertimage(context.getContentResolver(),b,"Title",null);
Uri imageUri = Uri.parse(path);
share.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
share.putExtra(Intent.EXTRA_STREAM,imageUri);
context.startActivity(Intent.createChooser(share,"Select"));
}
但我有这个问题:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication,PID: 2347
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:1014)
at android.app.ContextImpl.startActivity(ContextImpl.java:990)
at android.content.Contextwrapper.startActivity(Contextwrapper.java:403)
at com.example.myapplication.SinglePhoto.shareImage(SinglePhoto.java:61)
at com.example.myapplication.SinglePhoto$1.onClick(SinglePhoto.java:45)
at android.view.View.performClick(View.java:7357)
at android.view.View.performClickInternal(View.java:7334)
at android.view.View.access$3600(View.java:808)
at android.view.View$PerformClick.run(View.java:28200)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7478)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
我尝试使用
share.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
但问题依然存在。 感谢帮助!
解决方法
您需要添加此标志不是为了分享意图,而是为了您开始活动的意图:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT,shareBody);
Intent startIntent = Intent.createChooser(sharingIntent,context.getResources().getString(R.string.app_name));
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startIntent);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。