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