2013-07-02 84 views
0

我设置了一个AlarmManager对象来启动服务。
由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); 

AlarmHandlingServiceonStartCommand(..., ..., ...)的作品,因为它有工作,当它有工作。没有任何问题:

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>

我试图调试,发现只有的android.content.ContextWrapper CLAS的registerReceiver (BroadcastReceiver receiver, IntentFilter filter)功能当我拨打stopService时,s被称为。

+0

你的onDestroy()中有什么? – NetStarter

+1

我对onDestroy无能为力。不是在stopService之后调用吗?并且我的stopService根本没有被调用... @覆盖 public boolean stopService(意图名称) { Log.e(TAG,“Service is stopped”); return super.stopService(name); } – smb

+1

Aaaaaa !!!!谢谢你非常非常,NetStarter :)我将代码从stopService移动到onDestroy,现在它的工作:) – smb

回答

0

从你的评论你没有做任何事情时,你的stopService被调用。

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

您必须使用onDestroy方法。

public void onDestroy() 

在API级别1

添加由系统调用,以通知它不能再使用并且被移除的服务。这个服务应该清理它所拥有的任何资源(线程,注册接收者等)。返回后,将不会有更多的调用这个服务对象,它实际上已经死了。 (请勿直接调用此方法)。

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

您必须拨打cancel方法AlarmManager

0

请尝试新的活动。

stopService(new Intent(this, AlarmHandlingService.class)); 
+0

OP调用它就像只有'stopService(new Intent(context,AlarmHandlingService。类));' – NetStarter