我设置了一个 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(..., ..., ...)
,AlarmHandlingService
因为它必须工作,当它必须工作。没有任何问题:
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;
}
但是,当打开一个新活动 (SomeActivity) 并且我调用stopService(...)
时,该服务不会停止:
stopService(new Intent(context, AlarmHandlingService.class)); //context = getApplicationContext();
这是我的服务类在清单中的声明:
<service android:name="***myPackageName***.AlarmHandlingService"></service>
我尝试调试并注意到只有当我调用registerReceiver (BroadcastReceiver receiver, IntentFilter filter)
.android.content.ContextWrapper
stopService