2010-08-20 64 views
4

我仍在使用基于位置的闹钟android应用程序。我有一个AlarmService类,用于启动通知和接近警报。我开始这项服务:如何停止Android服务的多个实例?

startService(intentAlarmService); 

我尝试使用停止服务:

Intent intentAlarmService = new Intent(this, AlarmService.class); 
stopService(intentAlarmService); 

这是发生了什么:该服务停止,但后来,当我开始在服务的另一实例(即退出应用程序,启动应用程序,启动服务) - 我发现(通过Toasts)服务的先前实例仍在运行。例如,在AlarmService类中,有一个带有onLocationChanged方法的LocationListener。因此,在这种方法中,我提出:

Toast.makeText(AlarmService.this, "AlarmTitle: " + mAlarmTitle, Toast.LENGTH_SHORT).show(); 

当我重新启动该服务,敬酒不断显示出来与前AlarmTitles,和当前AlarmTitle。

因此,当我尝试停止AlarmService时,有些东西不起作用 - 这可能是什么?

注意:当我重新安装应用程序时,服务停止。然后,当我开始服务时,只有当前的闹钟显示在吐司(我希望每次都会发生这种情况)。

我的服务有问题。任何想法我可以做什么?

谢谢。


代码我的应用程序:

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

回答

6

我发现(通过干杯),该服务的以前的实例仍在运行。

我的猜测是,你正在泄漏的服务,可能是无法调用removeUpdates()脱离你的LocationListener。从Android生命周期的角度来看,只有一个真正运行的服务副本,但是你正在阻止其他服务被垃圾收集。

此外,请用this替换出现的所有出现的getApplicationContext()

+0

我还是有点新到Android编程。我知道什么是内存泄漏,但是“泄漏服务”是什么意思?你能否提供一些关于我的应用程序出现问题的更多解释? 谢谢,我对getApplicationContext()的出现感到抱歉。 – 2010-08-20 04:00:51

+0

@Yasir Malang:我相信你正在调用'registerLocationUpdates()'而不是调用'removeUpdates()'。 – CommonsWare 2010-08-20 04:16:24

+0

谢谢你的帮助。我查看了我的代码,发现了3个单独的LocationListener类的实现。我这样做是因为我不知道如何从另一个班级访问1个公共班级。你将如何编写代码来创建1个公共LocationListener类,然后让其他类继承它? – 2010-08-20 20:34:17

0

测试:

private Boolean Tb = true; 
if(condition) 
{ 
    if(Tb) 
    { 
    Toast.makeText(getApplicationContext(),"content...", Toast.LENGTH_LONG).show();    
    } 
Tb =false; 

final Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
    @Override 
      public void run() { 

      Tb =true; 
     } 
     }, Toast.LENGTH_LONG); 

    } 
}