2014-02-08 57 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 :-)