package com.lidaochen.test001; import android.content.Intent; import android.content.IntentFilter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { private ScreenReceiver screenReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 動態註冊廣播接收者 screenReceiver = new ScreenReceiver(); // 建立IntentFilter對象 IntentFilter filter = new IntentFilter(); // 添加要註冊的action filter.addAction("android.intent.action.SCREEN_OFF"); filter.addAction("android.intent.action.SCREEN_ON"); // 動態註冊廣播接收者 registerReceiver(screenReceiver, filter); } }
package com.lidaochen.test001; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class ScreenReceiver extends BroadcastReceiver { // 當咱們進行屏幕鎖屏和解鎖時,執行下面的方法 @Override public void onReceive(Context context, Intent intent) { // 獲取當前廣播的事件類型 String action = intent.getAction(); if("android.intent.action.SCREEN_OFF".equals(action)) { System.out.println("鎖屏!"); Log.e("screen","鎖屏"); } else if("android.intent.action.SCREEN_ON".equals(action)) { System.out.println("解鎖!"); Log.e("screen","解鎖"); } } }