0

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();
    }
}
Prophet
  • 32,350
  • 22
  • 54
  • 79
Phil
  • 583
  • 4
  • 7
  • 19
  • 1
    I believe the way to achieve your desired behavior would be to register your `BroadcastReceiver` class in your manifest, and then enable/disable it in the `onPause`/`onResume` methods using `PackageManager.setComponentEnabledSetting()`. – Mike M. Jun 26 '14 at 11:24
  • onPause/onResume fires to often and not exact at the described moments, that why i can't really use this methods – Phil Jun 26 '14 at 11:29
  • Oop, sorry, missed that part. However, those methods are about the only way you have of knowing when an Activity is put the background/brought to the fore. How exactly are they firing irregularly for you? – Mike M. Jun 26 '14 at 11:35

1 Answers1

1

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;)

axl coder
  • 739
  • 3
  • 19
  • That would help for 1 part of the problem, when the phone is locked, but how to check if the app is in background so not active? – Phil Jun 26 '14 at 11:28
  • For this it depends on the Android version on which your application is running. Lock at this answer http://stackoverflow.com/questions/3667022/android-is-application-running-in-background – axl coder Jun 26 '14 at 11:45