1

I've a Broadcast receiver:

public class ScreenReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {

          //Do something

        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {

            Intent start=new Intent(context,MainActivity.class);
        context.startActivity(start);
        }
    }
}

And, in my activity, into onCreate():

IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
ScreenReceiver mReceiver=new ScreenReceiver();
registerReceiver(mReceiver, filter);

The problem is that, when my activity is displayed, the receiver performs correctly the action, but when it is in background, sometimes nothing happens.

What could be the issue?

user1071138
  • 656
  • 3
  • 12
  • 30
  • See the answer to this post too: http://stackoverflow.com/questions/7890363/broadcastreceiver-and-paused-activity – Trinimon Apr 10 '13 at 17:05

1 Answers1

0

Most likely, when your app goes into the background Android kills it to free up resources. Try starting a foreground service attached to an ongoing notification from your Activity, and register the BroadcastReceiver in that.

Community
  • 1
  • 1
Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
  • I tried to add it to a service: public class KillVPNService extends Service { ScreenReceiver mReceiver; public void onCreate() { super.onCreate(); IntentFilter filter=new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); mReceiver = new ScreenReceiver(); registerReceiver(mReceiver, filter); } @Override public IBinder onBind(Intent intent) { return null; } } and in my activity: startService(new Intent(this,KillVPNService.class)); But I did not solve the problem... – user1071138 Apr 11 '13 at 13:50