簡體   English   中英

在線程中創建無限循環的方法是什么? 安卓

[英]What is the way to make an infinite loop in a thread? android

我想在android中創建一個無限循環,以檢查某些應用程序是否處於活動狀態。 不使用太多cpu的最佳方法是什么?

也許是一個while循環或處理程序或什么?

謝謝,

彼得

使用處理程序

import android.os.Handler;

// Create the Handler
private Handler handler = new Handler();

// Define the code block to be executed
private Runnable runnable = new Runnable() {
    @Override
    public void run() {
      // Insert custom code here

      // Repeat every 2 seconds
      handler.postDelayed(runnable, 2000);
    }
};

// Start the Runnable immediately
handler.post(runnable);

要刪除runnable的執行:

handler.removeCallbacks(runnable);

你可以做點什么

while(true)

當你想退出時,請務必使用break時間。

你也可以這樣做:

boolean run = true;
while(run)
{
    if()//Whatever you want to cause the loop to stop.
    {
        run = false;
    }
}

我不會在線程中使用無限循環。 我會使用這樣的計划任務。 來自SO

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
     scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);

然后,您可以通過將TimeUnit更改為您需要線程運行的頻率來自定義運行頻率。

暫無
暫無

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

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