Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在线程中生成无限循环的方法是什么?安卓_Android_Multithreading_Loops - Fatal编程技术网

Android 在线程中生成无限循环的方法是什么?安卓

Android 在线程中生成无限循环的方法是什么?安卓,android,multithreading,loops,Android,Multithreading,Loops,我想在android中做一个无限循环,检查一些应用程序是否处于活动状态。 不使用太多cpu的最佳方法是什么 也许是一个while循环或者一个处理程序或者其他什么 谢谢 彼得你可以这样做 while(true) 要退出时,只需确保使用中断 你也可以这样做: boolean run = true; while(run) { if()//Whatever you want to cause the loop to stop. { run = false; }

我想在android中做一个无限循环,检查一些应用程序是否处于活动状态。 不使用太多cpu的最佳方法是什么

也许是一个while循环或者一个处理程序或者其他什么

谢谢


彼得

你可以这样做

while(true)
要退出时,只需确保使用
中断

你也可以这样做:

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

我不会在线程中使用无限循环。我会使用这样的计划任务。从

然后,您可以通过将
时间单位更改为运行线程所需的频率来自定义线程的运行频率。

使用:

要删除runnable的执行,请执行以下操作:

handler.removeCallbacks(runnable);

为了避免错误“runnable可能尚未初始化”,我在
runnable
声明
final runnable[]runnables=new runnable[1]之前创建了一个数组handler.postDelayed
替换为这行
handler.postDelayed(runnables[0],2000)我是初学者。我的课程说我应该避免内部类,因为它可能会导致内存泄漏。那么这不会导致同样的结果吗?
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);
handler.removeCallbacks(runnable);