Broadcast Receiver是指广播接收器,处理的是系统级别的,
事件的广播机制哈是构建Intent对象,再调用sendBroadcast()方法将广播发出去,事件的接受则是通过继承一个BroadcastReceiver的类来实现,覆盖其onReceive()方法。
Android 系统中定义了很多标准的Broadcast Action来响应系统广播事件,如ACTION_TIME_CHANGED(时间改变时触发), ACTION_BOOT_COMPLETED(系统启动完成后触发), ACTION_PACKAGE_ADDED(添加包时触发),ACTION_BATTERY_CHANGED(电量低时触发)
当然也可以自定义Action,本文是自定义的Action
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:text="发出广播..."
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
MainActivity.java
package com.ex;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private static final String MY_ACTION ="com.ex.action.MY_ACTION";
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn=(Button)findViewById(R.id.btn_send);
btn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();//实例化intent对象
intent.setAction(MY_ACTION);//设置Intent Action属性
//为Intent添加附加信息
intent.putExtra("msg", "我是木小空,收到请你回复!");
//发布广播
sendBroadcast(intent);
}
});
}
}
MyReceiver.java
package com.ex;
//接收广播
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
//从Intent中获得信息
String msg=intent.getStringExtra("msg");
//使用Toast显示
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}
}
AndroidManifest.xml
<receiver android:name=".MyReceiver"
android:label="@string/app_name">
<intent-filter>
<action android:name="com.ex.action.MY_ACTION"/>
</intent-filter>
</receiver>
效果:
总结:1)既然要发出广播,就要一个发出广播的类(当然也可以有多个) ,构建Intent对象,然后sendBroadcast(intent对象)
2)需要一个接受广播的类,且这个类是继承BroadcactReceiver.要先接收intent中的信息
3)别忘了要在AndroidManifest里进行receiver的注册。