2013-07-02 129 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