Reputation: 418
I am using an alarmmanger with broadcast receiver and when a specified time occurs, i need to update the MainActivity with extra parameter but its behaving randomly.
here is code in the broadcast receiver
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);
}
}
In logcat, i am able to see "sleep" , so i know the method is being called at the right time
Here is code in MainActivity
//inside on create
//get value from shared preference and check
if(!isSleepMode){
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}else{
//do nothing
}
The user will most likely be already in that activity but not necessarily. The activity is being called for some devices and the screen turns off as expected but for some others, the activity is never called from the intent and screen wont turn off.
From the documentation, Intent.FLAG_ACTIVITY_CLEAR_TASK, should clear the activity before calling it again or am i missing something?
Is there a better way to update the activity from the receiver without calling it again?
Edit: My app is a launcher, does it in any way effect calling the intent?
Upvotes: 1
Views: 137
Reputation: 441
Another way to update the activity is by using Dynamic Broadcast receiver
To acheive this inside the onReceive Method use sendBroadcast to send the data to activity ad inside the activity register the broadcast Receiver to receive the data
Register your dynamic broadvast Receiver inside onCreate() and unregister inside onDestroy()
Upvotes: 0
Reputation: 418
I found a workaround using Intent.FLAG_ACTIVITY_SINGLE_TOP and overriding onNewIntent in the MainActivity. If the activity is already in the top, it calls onNewIntent otherwise creates a new instance of the activity. So the new code is like this
gotoSmileyScreen.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP );
and it works. Hope it helps someone.
Upvotes: 2
Reputation: 3520
Change your intent as below and try
Intent gotoSmileyScreen = new Intent();
gotoSmileyScreen.setClassName("com...<Your broadcast receiver name>", "com.....MainActivty.class");
gotoSmileyScreen.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(gotoSmileyScreen);
For Broadcast receiver try like above.
Upvotes: 0