我想从活动(如切换按钮)启动/停止服务,但它不会停止。
MainActivity.class
btnGoToTrack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SendIntentService.class);
boolean isServiceRunning = isServiceRunning(SendIntentService.class);
if (isServiceRunning == false) startService(intent);
else stopService(intent);
}
});
检查服务是否在线:
private boolean isServiceRunning(Class<?> pClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (pClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
问题是isServiceRunning
总是让我返回 TRUE。我不知道为什么。
SendIntentService.class:
@SuppressLint("NewApi")
public class SendIntentService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("D: ", "SERVICE STARTED !");
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("D: ", "SERVICE DISABLED !");
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}