更新/重启Android服务首选项

时间:2017-05-03 10:52:01

标签: java android android-service android-sharedpreferences

我对Android很新,所以这可能是一个非常基本的问题:

我有一个服务,当用户按下按钮

时启动

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

在服务的OnStart()方法中获取首选项:

at org.apache.spark.sql.hive.client.HiveClientImpl.<init> HiveClientImpl.scala:188)

并设置设置,例如:

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

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

我尝试使用以下命令重新启动服务:

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

但无论如何这不起作用。

提前感谢您的答案。

1 个答案:

答案 0 :(得分: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