发送广播
Intent intent = new Intent();
intent.putExtra("msg","hello,world!");
sendBroadcast(intent);
创建广播接收器
public class BatteryBroadcastReceiver extend BroadcastReceiver {
private Activity activity;
public DemoRecceiver(Activity activity) {
this.activity = activity;
}
@Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
((TextView)activity.findViewById(R.id.tv1)).setText("当前电量:" + persent);
Log.e("onReceive:", "当前电量:" + persent);
}
}
注册广播接收器
静态注册(在AndroidManifest.xml中注册)
<receiver android:name=".DemoRecceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BATTERY_CHANGED"/>
</intent-filter>
</receiver>
Android8.0(API26)之后某些广播不能静态注册详细参照隐式广播例外情况
动态注册
BatteryBroadcastReceiver receiver = new BatteryBroadcastReceiver(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter intentFilter = new IntentFilter();
intentFilter.setAction(Intent.ACTION_EXTRA_BATTER);
registerBroadcast(receiver,intentFilter);
}
注销广播接收器
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
|