Android学习笔记之Broadcast机制

静态注册

  • 继承BroadcastReceiver父类,重写onReceive方法。
  • 在AndroidManifest.xml中静态注册
public class BatteryLowReceiver extends BroadcastReceiver{
    private String TAG = "BatteryLowReceiver";
    @Override
    public void onReceive(Context context, Intent intent){
        Log.d(TAG,"action = " + intent);
    }
}

    
        
    

动态注册

private BroadcastReceiver mBatteryReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context,Intent intent){
        Log.d(TAG,"action = " + intent.getAction());
    }
}
@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    registerReceiver();
}

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

void registerReceiver(){
    mFilter = new IntentFilter();
    mFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(mBatteryReceiver, mFilter);
}

生命周期

Broadcast生命周期十秒左右,如果需要完成耗时工作,不能用子线程完成,可以用intent发送给Service.

你可能感兴趣的:(Android学习笔记)