IntentService中反复运行Android的运行功能

时间:2012-03-21 23:32:20

标签: java android android-intent

我有这个运行服务一次的IntentService代码:

protected void onHandleIntent(Intent intent) {
    final ResultReceiver receiver = intent.getParcelableExtra("receiver");
    String command = intent.getStringExtra("command");
    Bundle b = new Bundle();
    b.putString("results", results);
    if(command.equals("query")) {
        receiver.send(1, Bundle.EMPTY);
        try {                   
            results = sendGetMessage();
            b.putString("results", results);
            receiver.send(2, b);
        } catch(Exception e) {
            b.putString(Intent.EXTRA_TEXT, e.toString());
            receiver.send(0, b);
        }    
    }
    this.stopSelf();
    Log.d("ServiceFinished", "ServerConnection.java Service has finished");
}

我希望我的sendGetMessage()函数每5秒重复运行一次,直到我停止服务..我该怎么办?

2 个答案:

答案 0 :(得分:3)

你想把它放在自己的Thread中并永远循环它。

Thread thread = new Thread()
{
    @Override
    public void run() {
        try {
            while(true) {
                Thread.sleep(5000); // for the 5 seconds requirement
                results = sendGetMessage();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};

thread.start();

答案 1 :(得分:0)

有很多选择,但我更喜欢使用ScheduledExecutorService。请参阅以下示例代码:

ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(1);

// This schedule a task to run every 5 seconds:
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
  public void run() {
    // Do the actual job:
    results = sendGetMessage();

    // In case if you need update UI, simply do this:
    runOnUiThread(new Runnable() {
      public void run() {
        // update your UI component here.
        myTextView.setText("refreshed");
      }
    }); // end of runOnUiThread
  }
}, 0, 5, TimeUnit.SECONDS);

请记住在停止服务之前正确完成/关闭可运行的任务。