开发者

BroadcastReceiver for screen lock not being triggered

开发者 https://www.devze.com 2023-04-11 19:33 出处:网络
I\'m trying to turn the GPS location updates off when the screen locks. Having read the answer to this question Android - how to receive broadcast intents ACTION_SCREEN_ON/OFF?

I'm trying to turn the GPS location updates off when the screen locks. Having read the answer to this question Android - how to receive broadcast intents ACTION_SCREEN_ON/OFF?

I've written some code to implement a BroadcastReceiver but it's not working when the screen goes of开发者_如何转开发f.

I've registered a BroadcastReceiver in my code with

@Override
public void onResume() {
    super.onResume();
    IntentFilter iFilter = new IntentFilter();
    iFilter.addAction("android.intent.action.ACTION_SCREEN_ON");
    iFilter.addAction("android.intent.action.ACTION_SCREEN_OFF");
    registerReceiver(screenStatReceiver, iFilter);

and the receiver itself is just a stub for now:

    public BroadcastReceiver screenStatReceiver = new BroadcastReceiver() {

       @Override
       public void onReceive(Context context, Intent intent) {
       // TODO Auto-generated method stub
       Log.d("BCAST_TAG", "Got broadcast");         
       String action = intent.getAction();

       }
};

and in the manifest I have:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Any ideas as to why it's not being triggered when I debug it on my phone?


For this problem, you have to create a infinite service, which is registering a local broadcast receiver for these intents. If you do this way, then your app will look for screen off but make sure you have to make service which will always running in background like reboot receiver


You are registering the reciever in the onResume() method. Why dont you register it in the onCreate() so you can have persistent "listening"?

In this case you are listening for changes only after the activity is resumed.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号