我仍在研究基于位置的警报android应用程序。我有一个AlarmService类,可以启动通知和接近警报。我开始使用以下服务:
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();
当我重新启动服务时,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();
}
答案 0 :(得分:6)
我发现(通过Toasts)以前的服务实例仍在运行。
我的猜测是你正在泄漏服务,可能是因为没有致电removeUpdates()
来分离你的LocationListener
。该服务只有一个真正的运行副本(从Android生命周期的角度来看),但是您正在阻止其他服务通过泄漏进行垃圾回收。
另外,请将所有getApplicationContext()
替换为this
。
答案 1 :(得分: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);
}
}