android动态注册广播监听服务demo
服务类,一定要在清单文件中注册
public class lightService extends Service { private boolean ifrun = false; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { super.onCreate(); System.out.println("onCreate"); } public void onStart(Intent intent, int startId) { super.onStart(intent, startId); System.out.println("onStart"); if (ifrun) { return; } Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { Intent intent = new Intent(); intent.setAction("com.hnjd"); sendBroadcast(intent); } }, 0, 2 * 1000); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); System.out.println("onDestroy"); ifrun = false; } }
广播代码
class myboad extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { System.out.println("收到广播。。。"); jieXi(); } }
动态注册广播
private myboad b; private IntentFilter intentFilter; intentFilter = new IntentFilter(); intentFilter.addAction("com.hnjd"); if (isChecked) { System.out.println("状态打开"); Intent intent = new Intent(MainActivity.this, lightService.class); startService(intent); registerReceiver(b, intentFilter); } else { System.out.println("状态关闭"); unregisterReceiver(b); Intent intent = new Intent(MainActivity.this, lightService.class); stopService(intent); }