- 静态方式 创建一个类继承BroadcastReceiver
public class MyBroadCastReceiver01 extends BroadcastReceiver{ /** * 就一个生命周期 普通广播10s */ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub }}
并在manifest中<application>
标签中写
那么你将可以接受意图相同的广播
或者发送广播时指定你(此时意图可不写) 如:package com.qf.day22_broadcastreceiver_demo1;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } //发送广播 public void MySendClick(View v){ Intent intent = new Intent(MainActivity.this, MyBroadCastReceiver01.class); intent.putExtra("str", "疯狗咬人"); //发送普通的广播 sendBroadcast(intent); }}
- 动态方式 随便一个类继承BroadcastReceiver 内部类也可
BroadcastReceiver receicer=new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub } };
注册权限
//获取意图过滤器 IntentFilter intentFilter = new IntentFilter(); //添加Action intentFilter.addAction("qq.weixin.mm");registerReceiver(receicer, intentFilter);
一般我们在onresume注册 然后在onstop取消注册
取消注册
unregisterReceiver(receicer);
发送广播两种方法
普通广播 :其他广播接受则无法阻拦或者修改广播发送其他接受者Intent intent = new Intent();intent.setAction("cctv.hlj.beijin");intent.putExtra("str", "iphone7");//普通广播 sendBroadcast(intent);
有序广播根据广播接受顺序发送 ,其他广播接受者可以接受修改此广播在发送给其他人
Intent intent = new Intent(); intent.setAction("cctv.hlj.beijin"); intent.putExtra("str", "iphone7"); //有序广播1 sendOrderedBroadcast(intent, null); //有序广播2 并设置最终接受者 不管abortBroadcast();依然最后收到 sendOrderedBroadcast(intent, null,new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub } }, null, 0, null, null);