我正在使用带有广播接收器的闹钟管理器,当指定时间发生时,我需要使用额外参数更新MainActivity,但其行为是随机的。
这是广播接收器中的代码
public void onReceive(Context context, Intent intent){
//calculate time
//check time
if(isTime){
Log.d("tag", "sleep");
//set value in shared preference
editor = (context.getSharedPreferences("uniqueId", 0)).edit();
editor.putBoolean("sleepmode",false);
editor.apply();
Intent gotoSmileyScreen = new Intent(context, MainActivty.class);
gotoSmileyScreen.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK );
context.startActivity(gotoSmileyScreen);
}
}
在logcat中,我能够看到“睡眠”,所以我知道在正确的时间调用该方法
以下是MainActivity中的代码
//inside on create
//get value from shared preference and check
if(!isSleepMode){
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}else{
//do nothing
}
用户很可能已经参加了该活动但不一定。 某些设备正在调用该活动,屏幕将按预期关闭,但对于其他设备,活动永远不会从意图调用,屏幕也不会关闭。
从文档中,Intent.FLAG_ACTIVITY_CLEAR_TASK应该在再次调用之前清除活动,还是我错过了什么?
有没有更好的方法从接收器更新活动而不再调用它?
编辑:我的应用是一个启动器,以任何方式影响调用意图吗?
答案 0 :(得分:2)
我找到了使用Intent.FLAG_ACTIVITY_SINGLE_TOP并在MainActivity中覆盖onNewIntent的解决方法。如果活动已经在顶部,则调用onNewIntent,否则创建活动的新实例。所以新代码就像这样
gotoSmileyScreen.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP );
它有效。希望它可以帮到某人。
答案 1 :(得分:0)
如下更改您的意图并尝试
Intent gotoSmileyScreen = new Intent();
gotoSmileyScreen.setClassName("com...<Your broadcast receiver name>", "com.....MainActivty.class");
gotoSmileyScreen.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(gotoSmileyScreen);
对于广播接收器,尝试如上所述。
答案 2 :(得分:0)
更新活动的另一种方法是使用动态广播接收器
要在onReceive方法中实现此功能,请使用sendBroadcast将数据发送到活动内的活动广告 注册广播接收器以接收数据
在onCreate()中注册动态broadvast Receiver,并在onDestroy()内取消注册