我设置一个AlarmManager对象来启动服务。
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); //context = getApplicationContext();
Intent alarmServiceIntent = new Intent(context, AlarmHandlingService.class);
alarmServiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
alarmServiceIntent.putExtra("alarmId", _id); //_id is a "long" value
PendingIntent pi = PendingIntent.getService(context, (int)_id, alarmServiceIntent, 0);
am.set(AlarmManager.RTC_WAKEUP, time, pi);
onStartCommand(..., ..., ...)
的{{1}}可以正常工作,必须工作。没有任何问题:
AlarmHandlingService
但是,当打开一个新活动(SomeActivity)并且我调用public int onStartCommand(Intent intent, int flags, int startId)
{
long alarmId = intent.getLongExtra("alarmId", -1);
Intent someActivityIntent = new Intent(this, SomeActivity.class);
someActivityIntent.putExtra("alarmId", alarmId);
someActivityIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(someActivityIntent);
return START_NOT_STICKY;
}
时,服务不会停止:
stopService(...)
这是清单中我的服务类的声明:
stopService(new Intent(context, AlarmHandlingService.class)); //context = getApplicationContext();
我尝试调试并注意到当我调用<service android:name="***myPackageName***.AlarmHandlingService"></service>
时,registerReceiver (BroadcastReceiver receiver, IntentFilter filter)
类的android.content.ContextWrapper
函数被调用。
答案 0 :(得分:0)
请尝试新活动。
stopService(new Intent(this, AlarmHandlingService.class));
答案 1 :(得分:0)
从你的评论中,你在调用stopService时没有做任何事情。
当你调用stopService时,它实际上会调用函数stopService()。(在你的应用程序中完成)。
您必须使用onDestroy方法。
public void onDestroy ()
在API级别1中添加
由系统调用以通知服务它已不再使用且正在被删除。该服务应该清理它所拥有的任何资源(线程,注册接收器等)。返回后,将不再有对此Service对象的调用,它实际上已经死了。 (不要直接调用此方法)。
另一个问题是你没有打电话给你的警报管理员。
您必须为AlarmManager
调用cancel方法。