0

我设置了一个 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.ContextWrapperstopService

4

2 回答 2

0

请尝试新活动。

stopService(new Intent(this, AlarmHandlingService.class));
于 2013-07-02T12:24:01.640 回答
0

根据您的评论,当您的 stopService 被调用时,您没有做任何事情。

当您调用 stopService 时,它​​实际上会调用函数 stopService()。(正在您的应用程序中完成)。

您必须使用 onDestroy 方法。

public void onDestroy ()

在 API 级别 1 中添加

由系统调用以通知服务它不再使用并且正在被删除。此时服务应该清理它持有的所有资源(线程、注册的接收器等)。返回后,将不再调用此 Service 对象,它实际上已死。(不要直接调用这个方法)。

另一个问题是你没有调用任何东西来阻止你的警报管理器。

你一定已经AlarmManager.

于 2013-07-02T12:25:27.613 回答