本文由PurpleSword(jzj1993)原创,转载请注明
原文网址 http://blog.csdn.net/jzj1993
Activity中编写
/**
* 广播接收器
*/
public class MsgReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.v("", "on receive");
}
}
private MsgReceiver msgReceiver;
void initReceiver() {
// 动态注册广播接收器
msgReceiver = new MsgReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.jzj.main.RECEIVER");
registerReceiver(msgReceiver, intentFilter);
}
@Override
protected void onDestroy() {
// 停止服务
// stopService(mIntent);
// 注销广播
unregisterReceiver(msgReceiver);
super.onDestroy();
}
Service中编写
Intent intent = new Intent("com.jzj.main.RECEIVER");// 广播Intent,可在Intent的Extra中放入数据
sendBroadcast(intent); // 发送广播
反过来在Service中注册Receiver,由Activity发送消息给Service也可以。
Manifest
需注册Activity和Service,Receiver是动态注册的,不需在Manifest中注册