android允许应用程序自由地发送和接收广播。
广播是通过Intent进行数据传递的。接收广播则通过Broadcast Receiver(广播接收器)实现.
广播分为:标准广播和有序广播。
标准广播:一种完全异步执行的广播,在广播发出之后,所有的广播接收器几乎都会在同一时刻接收到这条广播消息,因此它们之间没有任何先后顺序可言。
有序广播:广播接收器是有先后顺序的,优先级高的广播接收器就可以先收到广播消息,并且前面的广播接收器还可以截断正在传递的广播,这样后面的广播接收器就无法收到广播消息了。
注册广播的方式一般有两种,在代码中注册称为动态注册,在 AndroidManifest.xml 中注册称为静态注册。
静态注册较常见,步骤如下:
1.新建一个类继承BroadcastReceiver,重写onReceive()方法;
2.在AndroidManifest里面对BroadcastReceiver注册,阐明<intent-filter>包含的广播信息;
3.在AndroidManifest里面用<uses-permission>声明权限;
3.在Activity里,实例化intent,并用sendBroadcast()发出广播.
以下示例摘自《第一行代码》
public class MyBroadcastReceiver extends BroadcastReceiver{
public void onReceive(Context context,Intent intent){
Toast.makeText(context, "MyBroadcastReceiver", Toast.LENGTH_SHORT).show();
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcastreceiverdemo2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.broadcastreceiverdemo2.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyBroadcastReceiver" >
<intent-filter>
<action android:name="com.example.broadcastreceiverdemo2.MY_BROADCAST"/>
</intent-filter>
</receiver>
</application>
</manifest>
public class MainActivity extends Activity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent("com.example.broadcastreceiverdemo2.MY_BROADCAST");
sendBroadcast(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
效果如下:
点击按钮后,就会显示广播。如图所示: