如何停止Android服务的多个实例?

Yas*_*ang 4 android

我仍在研究基于位置的警报android应用程序.我有一个AlarmService类,可以启动通知和接近警报.我正在开始这项服务:

startService(intentAlarmService);
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下命令停止服务:

Intent intentAlarmService = new Intent(this, AlarmService.class);
stopService(intentAlarmService);
Run Code Online (Sandbox Code Playgroud)

这就是:服务停止,但是当我启动另一个服务实例(即退出应用程序,启动应用程序,启动服务)时 - 我发现(通过Toasts)服务的先前实例仍然是运行.例如,在AlarmService类中,有一个带有onLocationChanged方法的LocationListener.所以,在这个方法中,我把:

Toast.makeText(AlarmService.this, "AlarmTitle: " + mAlarmTitle, Toast.LENGTH_SHORT).show();
Run Code Online (Sandbox Code Playgroud)

当我重新启动服务时,Toasts会继续显示之前的AlarmTitles和当前的AlarmTitle.

因此,当我尝试停止AlarmService时,某些功能无效 - 这可能是什么?

注意:当我重新安装应用程序时,服务将停止实时.然后当我启动服务时,只有Toast中显示当前的AlarmTitle(我希望每次都这样).

我的服务有问题.任何想法我能做什么?

谢谢.


我的APP代码:

public void onDestroy() {
    super.onDestroy();

    Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);

    PendingIntent pendingIntentAlarm = PendingIntent.getBroadcast(getApplicationContext(), PENDING_INTENT_REQUEST_CODE1, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    pendingIntentAlarm.cancel();

    Intent intentAlarmService = new Intent(getApplicationContext(), AlarmService.class);

    stopService(intentAlarmService); 

    mNtf.cancel(NOTIFICATION_ID1);
    mNtf.cancelAll();  
}
Run Code Online (Sandbox Code Playgroud)

Com*_*are 6

我发现(通过Toasts)以前的服务实例仍在运行.

我的猜测是你正在泄漏服务,可能是因为没有打电话removeUpdates()来分离你的服务LocationListener.该服务只有一个真正的运行副本(从Android生命周期的角度来看),但是您正在阻止其他服务通过泄漏进行垃圾回收.

另外,请更换所有出现getApplicationContext()this.