一個內部類:BroadcastReceiver的子類,並定義收到廣播以後的操做:ide
1 class LockScreenBroadcastReceiver extends BroadcastReceiver{ 2 3 @Override 4 public void onReceive(Context context, Intent intent) { 5 //接收到廣播以後的操做 6 KLog.d("收到廣播"); 7 LockScreenNightRestActivity.this.finish(); 8 } 9 }
定義action和BroadcastReceiver子類對象:this
1 //定義關閉此activity的action 2 public static final String NIGHT_REST_ACTIVITY_FINISH = "night_rest_activity_finish"; 3 private LockScreenBroadcastReceiver broadcastReceiver;
onCreate中註冊:spa
1 @Override 2 protected void onCreate(Bundle savedInstanceState) { 3 super.onCreate(savedInstanceState); 4 5 // 1. 實例化BroadcastReceiver的子類對象 6 broadcastReceiver = new LockScreenBroadcastReceiver(); 7 IntentFilter intentFilter = new IntentFilter(); 8 // 2. 設置接收廣播的類型 9 intentFilter.addAction(NIGHT_REST_ACTIVITY_FINISH);// 只有持有相同的action的接受者才能接收此廣播 10 // 3. 動態註冊:調用Context的registerReceiver()方法 11 registerReceiver(broadcastReceiver, intentFilter); 12 }
onDestroy中註銷:rest
1 //銷燬onResume()中的廣播 2 unregisterReceiver(broadcastReceiver);