簡體   English   中英

在Android中每1秒在后台運行我的代碼一次

[英]Run my code in background every 1 sec effectively in Android

我必須每秒在后台運行一些代碼,該代碼將調用Web服務,該服務搜索數據庫並將值返回給應用程序。 我的問題是哪種方法最有效? 我已經閱讀了有關Timers,Threads,AsyncTask和Services的文章,並且似乎各有優缺點。 考慮到執行時間和電池壽命,請告訴我哪種才是最好的選擇。

謝謝

更新:我決定使用Aysnc任務在后台運行我的代碼,同時使用TimeTask定期觸發AsyncTask。 這樣,當我離開該特定活動時,該操作將被銷毀

您應該使用該服務執行后台操作,但是在您的情況下,您希望在1秒內運行代碼,以下是該服務示例,該服務使用每1秒調用一次的處理程序。

public class YourService extends Service {
private static final String TAG = "Your Service";
private final Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {

}
};
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
//  Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

}

@Override
public void onDestroy() {
    super.onDestroy();
//  Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    handler.removeCallbacks(sendUpdatesToUI);   
}
 private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            /// Any thing you want to do put the code here like web service procees it will run in ever 1 second
            handler.postDelayed(this, 1000); // 1 seconds
        }
 };
@Override
public void onStart(Intent intent, int startid) {

    handler.removeCallbacks(sendUpdatesToUI);
    handler.postDelayed(sendUpdatesToUI, 1000);//1 second       
    Log.d(TAG, "onStart");
}

}

和服務不能運行每一次android在3或4小時內空閑服務,我建議您使用前台服務來長時間運行您的進程。

對於此類操作,我傾向於使用服務組件。 對於任務本身,我使用AsyncTask,它將等待一段設置的時間,然后再重復自身(使用while循環)。

您將必須創建一個新Thread以便在調用花費比預期更長的時間時調用不會鎖定設備。 AsyncTask是使用多線程的一種簡便方法,但是它缺少重復任務的功能。 我要說的是,最好使用Timer或更新的ScheduledExecutorService 如果選擇使用Timer可以創建一個TimerTask來處理它。 ScheduledExecutorService改為使用Runnable。

您可能希望將線程包裝在Service (該服務不提供新的線程),但這並非總是必要的,具體取決於您的需求。

如注釋中所建議,您還可以使用Handler.postDelayed() 盡管您仍然需要創建一個新線程,然后在其上調用Looper.prepare()

  class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }

(來自Looper docs的代碼)

也; 每秒對Web服務的調用似乎太頻繁了,尤其是在用戶連接速度慢或需要傳輸數據的情況下,請嘗試盡可能減少調用。

我認為這不僅是一種解決方案,所以取決於您。 您可以嘗試使用以下運行方法啟動線程:

private final int spleeptime = 1000;
public boolean running;

@Override
public void run() {
    while (running) {
        try {
            int waited = 0;
            while ((waited < spleeptime)) {
                sleep(100);
                waited += 100;
            }
        } catch (InterruptedException e) {
        } finally {
            // your code here
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM