我通过点击按钮启动我的服务,并通过停止按钮停止我的服务。
我的服务类在下面给出
public class Services extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand (Intent intent,int flags, int startId){
Log.d("Services","Started...");
return START_NOT_STICKY;
}
@Override
public void onDestroy () {
super.onDestroy();
Log.d("Services","Stoped...");
}
}
我的Receiver课程在下面给出
public class Reciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//check the intent something like:
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (KeyEvent.KEYCODE_VOLUME_UP== event.getKeyCode()) {
Log.d("Volume","Down");
}
}
}
}
答案 0 :(得分:0)
首先删除清单中的互联网过滤器然后。在您正在启动服务的Activity
,以及注册您的BroadcastReciver
,当您停止服务活动时,停止取消注册BroadcastRecived
注册
IntentFilter filter = new IntentFilter();
filter.addAction("SOME_ACTION");
filter.addAction("SOME_OTHER_ACTION");
receiver = new MyBroadcastReceiver();
registerReceiver(receiver, filter);
取消注册
if (receiver != null) {
unregisterReceiver(receiver);
receiver = null;
}