Android--------------BroadcastReceiver的学习

一、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的学习

Android--------------BroadcastReceiver的学习

上一篇:2021-10-15-torch.cat()


下一篇:移动端适配rem