如何在重新启动后停止服务 activity?

How to stop service even after restarting activity?

我想停止 activity 的服务。当我不关闭应用程序时它会停止。但是当我关闭应用程序并且 运行 应用程序再次服务不会停止。

流量:

--> 点击开启
--> 显示通知/位置侦听器
--> 杀死应用程序
--> 通知仍然存在(服务是 运行ning 的意思)
--> 再次打开应用程序
--> 单击关闭
--> 服务不会停止并且通知持续存在

服务Class

public class locationService extends Service {

NotificationCompat.Builder builder;
NotificationManager notificationManager;

public static final String serviceTag = "LocationServiceTag";


@Nullable
@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

@Override
public boolean onUnbind(Intent intent) {
    return super.onUnbind(intent);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    SharedPreferences sharedPref = getSharedPreferences("AppPref",Context.MODE_PRIVATE);
    userCurrentRoute= sharedPref.getString("RouteNo","");

    mDatabase = FirebaseDatabase.getInstance().getReference();

    notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);

    Intent repeating_intent =new Intent(this,MainActivity.class);

    PendingIntent pendingIntent= PendingIntent.getActivity(this,10,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);


     builder = new NotificationCompat.Builder(this)
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.drawable.bus_small)
            .setContentTitle("BusBuzz")
            .setContentText("Sharing Location to all")
            .setAutoCancel(false)
            .setOnlyAlertOnce(true)
            .setOngoing(true)
            ;

    notificationManager.notify(10,builder.build());

    provider = new LocationGooglePlayServicesProvider();
    provider.setCheckLocationSettings(true);

    return START_NOT_STICKY;
}

@Override
public void onCreate() {
    super.onCreate();
}


@Override
public void onDestroy() {
    notificationManager.cancel(10);
    Toast.makeText(this, "App Closed Location Sharing Stopped", Toast.LENGTH_SHORT).show();
    SmartLocation.with(this).location().stop();
    super.onDestroy();
}

}

Activity

 if (isChecked) {

                startService(new Intent(MainActivity.this,locationService.class).addCategory(locationService.serviceTag));

            }
            else
            {


                stopService(new Intent(MainActivity.this,locationService.class).addCategory(locationService.serviceTag));

            }

您写道:

--> Click Switch ON
--> Show Notification / Location Listener
--> Kill App
--> Notification still remains (Service is running means)

仅仅因为通知存在,并不意味着Service仍然是运行。实际上,它已经死了。你杀死了应用程序,它杀死了 Service,并且由于你从 onStartCommand() return START_NOT_STICKY,Android 不会重新启动 Service 直到你App 再次显式调用 startService()。由于应用程序被杀死,onDestroy() 从未被调用,因此通知从未被删除。

您可以通过使用 adb shell dumpsys activity services 查看您的 Service 是否是 运行 来验证这一点,在您关闭您的应用程序后。