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

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

我想通过服务 class 中的选项打开共享。 它在 Android 7 中工作正常,但在 8+ OS 中它开始显示

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

我也已将此标志添加到我的 Intent 中,但它仍然显示相同的错误。

有没有其他方法可以通过服务 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..."));

Intent.createChooser 创建一个 Intent,因此您需要在 那个 意图上设置 FLAG_ACTIVITY_NEW_TASK 标志,例如,

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

您还调用了 startService 而不是 startActivity - 请务必更正该错误。