how to get broadcast for screen lock in android

前端 未结 2 668
轻奢々
轻奢々 2021-01-02 22:29

How to get trigger that screen is locked or on in android?? i tried using SCREEN_OFF & SCREEN_ON action in broadcast receiver but it\'s not working.

publ         


        
2条回答
  •  滥情空心
    2021-01-02 23:05

    Hey try using dynamic calling of broadcast,I tried this it will surly work...

    public class MainActivity extends Activity {
         //Create broadcast object
           BroadcastReceiver mybroadcast = new BroadcastReceiver() {
    
            //When Event is published, onReceive method is called
            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                    Log.i("[BroadcastReceiver]", "MyReceiver");
    
                    if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
                        Log.i("[BroadcastReceiver]", "Screen ON");
                    }
                    else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
                        Log.i("[BroadcastReceiver]", "Screen OFF");
                    }
    
            }
        };
    
         @Override
           public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
    
           registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_ON));
           registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
         }
        }
    

提交回复
热议问题