2014-02-08 89 views
0

我正在使用Android AlarmManger來安排IntentService在小間隔後運行。Android IntentService僅執行一次

這裏是我的AlarmManger:

static void setNextSchedule(Context ctx, long interval){ 
     AlarmManager manager = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE); 
     Intent nIntent = new Intent(ctx, DService.class); 
     PendingIntent pIntent = PendingIntent.getActivity(ctx, 1, nIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

     manager.setRepeating(AlarmManager.ELAPSED_REALTIME, 
       SystemClock.elapsedRealtime() + interval, interval, pIntent); 

     Log.i(ScheduleAlarm.class.getSimpleName(), "Next alarm set"); 
    } 

而且我IntentService:

@Override 
    protected void onHandleIntent(Intent intent) { 
     Log.i(DService.class.getSimpleName(), "Service starting"); 

     ScheduleAlarm.setNextSchedule(getApplicationContext(), 15000); 
    } 

目前,它只是持有的代碼進行測試。 現在,這個代碼將成功運行,一旦應用程序啓動時沒有問題,但15秒後它將聲明服務在logcat中啓動,但代碼不會執行

如何讓intenet服務在每次運行時執行onHandleIntent內的代碼?

感謝

+0

「但代碼將不會執行」 - 什麼是「代碼」?你如何確定它「不會執行」?爲什麼你對一個名爲'DService'的類使用getActivity()''PendingIntent'作爲'Intent'? – CommonsWare

+0

@CommonsWare - 你是對的,改成'getService()',現在一切正常。添加爲答案,我會接受。謝謝 – Wahtever

回答

1

當使用PendingIntent,工廠方法需要匹配組件的類型,你Intent是:

  • 如果您Intent指向一個活動,請使用getActivity()

  • 如果您的Intent指向某項服務,請使用getService()

  • 如果您Intent指向BroadcastReceiver,使用getBroadcast()

  • 如果您Intent點以上都不是,直接去坐牢,不傳去!不收$ 200 :-)