通过 manifest 注册 ,特点是 关闭应用程序后 ,广播接收依然存在
首先在 Action 中设置 onclick 监听 通过intent 发送 broadcast 到 broadcastrecerver
public class Broad2Activity extends Activity {
/** Called when the activity is first created. */
private Button button_1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button_1 = (Button)findViewById(R.id.button1);
button_1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction(Intent.ACTION_EDIT); // 这里的action事件必须和Manifest 里面的对应
Broad2Activity.this.sendBroadcast(intent); //发送braod cast
}
});
}
}
然后 需要在 Manifest 中注册receiver广播事件, 其中Action 的类型要和 intent.setAction 里面的一致
android:name=".Recerver" 也要和 将创建的 接受广播 boradCastRecerver 类名一致
<receiver android:name=".Recerver"> <intent-filter > <action android:name="android.intent.action.EDIT"/> </intent-filter> </receiver>
然后 是新建 Recerver 类 继承 BroadcastReceiver 并复写 onReceive 事件
public class Recerver extends BroadcastReceiver{
public Recerver (){
System.out.println("准备接收");
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println("在做接收了哦.");
}
}