【问题标题】:This is the correct way to repeat method every x second in service?这是在服务中每 x 秒重复一次方法的正确方法吗?
【发布时间】:2014-07-09 12:40:40
【问题描述】:

我在服务上编写了一个方法,每 x 秒运行一次。但是也有一些问题。

我做的是

public class noti extends Service  {
      Context mcont; 
      private Handler myhandler ;
      private long RETRY_TIME = 15000; 
      private long START_TIME = 2000; 

  @Override
  public IBinder onBind(Intent intent) {
      // TODO: Return the communication channel to the service.
      throw new UnsupportedOperationException("Not yet implemented");
  } 

  @Override
  public void onStart(Intent intent, int startId) { 

  }
  @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     mcont=this;
     myhandler= new Handler();
     myhandler.postDelayed(myRunnable, START_TIME);
     return super.onStartCommand(intent, flags, startId);

    }
    @Override
  public void onDestroy() { 
        super.onDestroy();  
        try {
            myhandler.removeCallbacks(myRunnable); 
        } catch (Exception e) {
            // TODO: handle exception
        }
  }



    private Runnable myRunnable = new Runnable() {
           public void run() { 
           try {
                new get_notifyalert_service(mcont).execute("")  ; 
            } catch (Exception e) {
                // TODO: handle exception
            }  
            myhandler.postDelayed(myRunnable, RETRY_TIME);
           }
        };
}

这是正确的方法吗?

当我在手机上检查 settings->apps->running-apps 时显示有时会重新启动并且需要很长时间

提前致谢

【问题讨论】:

  • 为什么不使用AlarmManager...一旦服务以任何方式停止,您当前的实现将不会再次被调用。但警报管理器会。
  • 你能分享任何链接吗?谢谢
  • 你为什么不直接用谷歌搜索 :)
  • 好的,感谢您的回答
  • @SMR 我可以用 alarmmanager 运行我的方法吗,因为我可以看到我们可以用 alarmmanager 使用意图

标签: java android android-service android-handler


【解决方案1】:

我在您的解决方案中发现了两个问题:

首先:您的命令确实会定期激活,但它们会这样做on the main thread。在许多情况下,也许是大多数情况下,您希望定期处理在单独的线程上运行。


如果这是您想要的,计时器将是更好的选择:


  t = new Timer();
  task = new TimerTask() {
       @Override
       public void run() {
           // do periodical action <-------------
       }
  };
  t.scheduleAtFixedRate(task, 0, 1000);


第二:你的服务迟早会被 Android 回收,停止定期 处理。

对于许多应用来说,这不是一个真正的问题。您并不真的希望您的后台逻辑一直一直运行。

如果您不是这种情况,请将您的服务声明为前台服务(即保证不会被 Android 杀死):


Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);


..或者,至少,将其设置为粘性:

public class StickyService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
         return Service.START_NOT_STICKY;
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 2019-02-01
    • 2012-07-11
    • 1970-01-01
    • 2018-06-06
    相关资源
    最近更新 更多