2017-05-03 84 views
0

我非常新的Android所以这可能是非常基本的问题:更新/重新启动的Android服务首

我有一个开始,当用户按下一个按钮

该服务将启动一个新的任务服务并每N秒循环一次。 秒数在我的Android应用程序的“设置”选项卡上设置。

在服务的OnStart()方法获得的首选项。

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 

,并设置设置,例如:

final Long pollInterval = Long.parseLong(settings.getString("pollInterval", "1000")); 

任务是对新entrys数据库查询。 我的目标是在返回主框架后重新启动服务,以便onCreate方法获得新的首选项或刷新正在运行的任务中的首选项以更改轮询间隔。

我试图重新启动与服务:

startService(serviceIntent); 
stopService(serviceIntent); 

但出于某种原因,这并不工作。

在此先感谢您的答案。

回答

0
Use this one to repeat service 



try { 

      //Create a new PendingIntent and add it to the AlarmManager 
      Intent intent = new Intent(this, Service.class); 
      PendingIntent pendingIntent = PendingIntent.getService(this, 
       12345, intent, PendingIntent.FLAG_CANCEL_CURRENT); 
      AlarmManager am = 
       (AlarmManager)getSystemService(Activity.ALARM_SERVICE); 
      am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 
        2*60*60,pendingIntent); 

      } catch (Exception e) {} 

Also stop service when your task is completed