什么是广播
①Android四大组件之一
②一种全局的监听器,用于监听系统全局的广播消息
③系统大部分消息都以广播的形式发布,比如开机启动完成的消息。收到短信的消息,打进打出电话的消息
广播的分类及区别——有序广播和无序广播
无序广播
- 所有监听该广播接受者都可以监听到该广播
- 同级别接收先后顺序是随机的(无序)
- 级别低的后收到广播
- 接收器不能截断广播的继续传播,也不能处理广播
有序广播
- 按照接收者的优先顺序来接收广播,优先级别在intent-filter中的priority中声明,-1000到1000之间,值越大优先级越高可以终止广播的继续传播,接受者可以修改intent的内容。
- 同级别接收顺序是随机的
- 级别低的后收到
- 能截断广播的继续传播,高级别的广播接收器接收广播后能决定时候截断。
- 能处理广播
广播的注册方式及区别——静态注册和动态注册
静态注册无序广播
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="com.example.MyReceiver.demo" />
</intent-filter>
</receiver>
静态注册有序广播
<receiver android:name=".MyReceiver">
//范围在-1000~1000,优先级越大越高
<intent-filter android:priority="100">
<action android:name="com.example.MyReceiver.demo" />
</intent-filter>
</receiver>
动态注册无序广播
MyReceiver myReceiver=new MyReceiver();
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("");
registerReceiver(myReceiver,intentFilter);
动态注册有序广播
MyReceiver myReceiver=new MyReceiver();
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("");
intentFilter.setPriority(1000);
registerReceiver(myReceiver,intentFilter);
适配器中发送广播
在适配器中发送广播需要通过context来调用sendBroadcast方法
Intent intent=new Intent();
intent.setAction("com.example.a17825.myapplication.price");
context.sendBroadcast(intent);
Service中发送广播
例如使用Service网络下载一张图片,再通过广播发送给Activity:
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url=new URL("http://b.hiphotos.baidu.com/image/pic/item/96dda144ad345982b391b10900f431adcbef8415.jpg");
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
InputStream inputStream=connection.getInputStream();
Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
Intent bitmapIntent=new Intent();
bitmapIntent.setAction("com.example.a17825.myapplication.background");
bitmapIntent.putExtra("bitmap",bitmap);
sendBroadcast(intent);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
}
Activity接受bitmap图片时要用getParcelableExtra方法:
Bitmap bitmap=intent.getParcelableExtra("bitmap");