Reputation: 583
I want the Broadcastreceiver
in my app to just start if the app gets into the background or the handy is on standby (locked). Therefore I tried it via onPause()
onDestroy()
and onResume()
but sometimes it activates/deactivates because the methods are fired unregulary. Is there a better solution to achieve my aim?
My code:
public void enableBroadcastReceiver(){
IntentFilter filter = new IntentFilter();
filter.addAction("com.google.android.c2dm.intent.RECEIVE");
filter.addAction("com.google.android.c2dm.intent.REGISTRATION");
filter.addCategory("xxx");
receiver = new GcmBroadcastReceiver();
registerReceiver(receiver, filter);
Toast.makeText(getApplicationContext(), "Enabled broadcast receiver", Toast.LENGTH_SHORT).show();
receiver_working = true;
}
public void disableBroadcastReceiver(){
try {
unregisterReceiver(receiver);
Toast.makeText(getApplicationContext(), "Disabled broadcst receiver", Toast.LENGTH_SHORT).show();
receiver_working = false;
} catch (IllegalArgumentException e) {
}
}
@Override
public void onResume() {
super.onResume();
if(receiver_working) {
disableBroadcastReceiver();
}
}
@Override
public void onPause() {
super.onPause();
if(!receiver_working) {
enableBroadcastReceiver();
}
}
@Override
public void onDestroy() {
super.onDestroy();
if(receiver_working) {
disableBroadcastReceiver();
}
}
Upvotes: 0
Views: 737
Reputation: 749
Maybe instead of disable your Receiver when your device is in sleep mode you could check this condition inside your receiver.
Inside your Receiver you can simply put an if that will check if there is an active application or not (for example you can check if the screen is turned off by calling isScreenOn method).
I hope this was what you were searching for;)
Upvotes: 1