简体   繁体   中英

Android Service does not stop

I want to start/stop a service from an activity (like a switch button), but it does not stop.

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);
   }
});

Check if service is online or not:

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;

The problem is isServiceRunning is always returning me TRUE. I don't know why.

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;
    }
}

"The problem is isServiceRunning is always returning me TRUE. I don't know why." shouldn't it be: "The problem is isServiceRunning is always returning me FALSE. I don't know why."?

If it would always return TRUE it wouldn't start the service...

Did you check if pClass.getName() really equals service.service.getClassName()?

The problem was with my AVD. I have several versions installed (while developing the app) and I think there was multiple services started.

I have removed all versions from my AVD (Settings -> Apps -> Uninstall app) and restarted the application. Now it's working !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM