从Activity上下文外部调用startActivity() - 建议修复不起作用

时间:2016-11-27 12:51:26

标签: android

我有一个闹钟应用程序 - 它在运行CM14的moto G3上运行得非常好,但在字面上每隔一个设备我都会收到此错误:

Unable to start service joelizsoftware.david.slide_puzzle_alarm_clock.RingtoneService@69b5bb9 with Intent { flg=0x10000000 cmp=joelizsoftware.david.slide_puzzle_alarm_clock/.RingtoneService (has extras) }: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

我已经按照SO的建议,并加入:

ringtoneIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

但我仍然得到同样的错误。有什么想法吗?

public class Alarm_Receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {



        String extraString = intent.getExtras().getString("extra");
        String prefString = intent.getExtras().getString("savePref");



        Intent ringtoneIntent = new Intent(context, RingtoneService.class);
        ringtoneIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        ringtoneIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        ringtoneIntent.putExtra("extra", extraString);
        ringtoneIntent.putExtra("savePref", prefString);



        context.startService(ringtoneIntent);

    }
}

这毁了我的星期天

2 个答案:

答案 0 :(得分:0)

似乎问题出现在RingtoneService。如果您从服务启动活动意图,则应将Intent.FLAG_ACTIVITY_NEW_TASK标志添加到活动意图中。

答案 1 :(得分:0)

试试这样:

public class Alarm_Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {



String extraString = intent.getExtras().getString("extra");
String prefString = intent.getExtras().getString("savePref");

    Intent i = new Intent();
    i.setClassName("com.test", "com.test.RingtoneService");
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
    i.putExtra("extra", extraString);
    i.putExtra("savePref", prefString);
    context.startActivity(i);




context.startService(ringtoneIntent);

}