Service demo如下:
public class ServiceDemo extends Service { private AutoExceptMsgReceiver autoExcepMstReceiver; @Override public IBinder onBind(Intent arg0) {//这是Service必须要实现的方法,目前这里面什么都没有做 return null; } @Override public void onCreate() { //在onCreate()方法中打印了一个log便于测试 super.onCreate(); LogUtil.showErrLog("MyServiece onCreate", "Service 已经启动成功"); //注册接收异常广播消息 autoExcepMstReceiver = new AutoExceptMsgReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction("deomo.demo.demoaction"); registerReceiver(autoExcepMstReceiver, filter); } //广播接收异常消息 private class AutoExceptMsgReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent != null) { LogUtil.showLog("------------------------------------收到异常信息广播"); } } } }
启动Service :
startService(new Intent(this, ServiceDemo.class));
发送广播 :
Intent intent=new Intent(
"deomo.demo.demoaction");
intent.putExtra("test", "test");
sendBroadcast(intent);