1. 程式人生 > >Android--------------BroadcastReceiver的學習

Android--------------BroadcastReceiver的學習

tag power () pow tac receive tex and lte

一、BroadcastReceiver的靜態註冊

  BroadCastRecevier.java文件

  public class BroadCastRecevier extends BroadcastReceiver {
   @Override
  public void onReceive(Context context, Intent intent) {
   Log.i("TAG", intent.getAction());
  }
}

  AndroidManifest.xml文件

  <receiver android:name=".BroadCastRecevier">
  <intent-filter >
    <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
  </intent-filter>
  </receiver>

二、BroadcastReceiver的動態註冊

  @Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  //這步相當於靜態註冊的方法
  IntentFilter filter = new IntentFilter();
  filter.addAction(Intent.ACTION_APP_ERROR);
  registerReceiver(BroadCRecevier, filter);
  }

  @Override
  protected void onDestroy() {
  super.onDestroy();
  unregisterReceiver(BroadCRecevier);
  }

  private BroadcastReceiver BroadCRecevier = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
  intent.getAction();
  }
 } ;

三、BroadcastReceiver生命周期----------》它的生命周期很短暫,只有不到10秒

  技術分享圖片

Android--------------BroadcastReceiver的學習