简体   繁体   English

广播接收器启动活动

[英]Broadcast receiver start activity

I have an application that using "AlarmService". 我有一个使用“ AlarmService”的应用程序。 For handling alarms i have a Broadcast receiver. 为了处理警报,我有一个广播接收器。 That receiver has to start certain activity. 该接收者必须开始某些活动。 Code i'm using for achieving that is following: 我用于实现以下目的的代码如下:

@Override
public void onReceive(Context context, Intent intent) {
    ...other code....
    Intent intIntent = new Intent(context, MainActivity.class);
    intIntent .putExtra("IsAlarm", true);
    Intent alarmChooser = Intent.createChooser(intIntent , "Alarm");
    alarmChooser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(alarmChooser);
}

That works but only if activity isn't shown already (if it's not in the foreground). 这有效,但前提是尚未显示活动(如果活动不在前台)。 If called activity is already opened nothing happens. 如果被叫活动已经打开,则什么也不会发生。 How can i overcome that? 我该如何克服呢? Is there a flag that will start the activity if it's not started OR send intent to it even if it's in the foreground? 如果没有启动活动,是否有一个标志将启动该活动,或者即使活动在前台也将向其发送意图?

PS i tried using dedicated "broadcast" above the provided code. PS我尝试在提供的代码上方使用专用的“广播”。 Reciever for that broadcast is registered programmatically in the MainActivity: "onResume" would register dedicated receiver, "onPause" would unregister it. 在MainActivity中以编程方式注册了该广播的接收者:“ onResume”将注册专用接收器,“ onPause”将取消注册它。 That way in case MainActivity is already on it will receive a broadcast but then i have a problem when phone goes to "stand by" - "dedicated" receiver is unregistered. 这样,如果MainActivity已经在它上面,它将接收广播,但是当电话转到“待机”时,我有一个问题-未注册“专用”接收器。

I think you don't need the chooser: 我认为您不需要选择器:

@Override
public void onReceive(Context context, Intent intent) {
    Intent intIntent = new Intent(context, MainActivity.class);
    intIntent.putExtra("IsAlarm", true);
    context.startActivity(intIntent);
}

在活动onNewIntent回调中onNewIntent入,接收者应该有新的意图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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