Android的广播机制方便了开发者接收系统及其他APP发送的广播(开机,电池电量改变等,那么如何自定义一个广播呢?下面来说说自定义广播的流程
****第一步****
先设置好一个独一无二的action(一个字符串),发送和接收广播都要依靠这个action,以下为例:
public static final String ACTION_MEMEDA = "com.shijianan.demo.memeda";-
****第二步****
新建BroadcastReceiver子类,重写onReceive方法
public class MemedaReceiver extends BroadcastReceiver {
public static final String ACTION_MEMEDA = "com.shijianan.demo.memeda";
public static final String EXTRA_MEMEDA = "memeda";@Override public void onReceive(Context context, Intent intent) { //一旦接收到通知,并且通知携带数据的话就吐司出来 if(intent!=null&&intent.hasExtra(EXTRA_MEMEDA)){ Toast.makeText(context, intent.getStringExtra(EXTRA_MEMEDA), Toast.LENGTH_SHORT).show(); } } }
-
****第三步****
注册并使用接收器
1,动态注册public class BroadcastActivity extends AppCompatActivity { private MemedaReceiver memedaReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_broadcast); initView(); registerReceiver(); } private void initView(){ findViewById(R.id.custom).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //发送一个通知 Intent intent = new Intent(MemedaReceiver.ACTION_MEMEDA); intent.putExtra(MemedaReceiver.EXTRA_MEMEDA,"memeda"); sendBroadcast(intent); } }); } private void registerReceiver(){ //初始化广播接收器对象,注册广播 memedaReceiver = new MemedaReceiver(); //这里的action就是一开始定义的那个action IntentFilter intentFilter = new IntentFilter(MemedaReceiver.ACTION_MEMEDA); registerReceiver(memedaReceiver,intentFilter); } @Override protected void onStart() { super.onStart(); //也可以在这里注册 } @Override protected void onStop() { super.onStop(); //如果在onStart()中注册在这里记得反注册 } @Override protected void onDestroy() { super.onDestroy(); //反注册 unregisterReceiver(memedaReceiver); } }
2,静态注册
- AndroidManifest中Application节点下添加如下代码
<receiver android:name=".broadcastreceive.MemedaReceiver">
<intent-filter>
<action android:name="com.shijianan.demo.memeda"/>
</intent-filter>
</receiver> - 要发送一个通知则如下所示
//MemedaReceiver.ACTION_MEMEDA的值等于刚才的action的值
Intent intent = new Intent(MemedaReceiver.ACTION_MEMEDA);
intent.putExtra(MemedaReceiver.EXTRA_MEMEDA,"memeda");
sendBroadcast(intent);