android - 服务中只有一个 Thread 实例

标签 android

我在服务中初始化了新的线程,但是当我开始服务时,新的线程就创建了,它使我的应用程序崩溃,因为我在其中使用了摄像头。 如何让它成为该线程的唯一一个实例?

线程何时关闭?如果我在创建它的地方关闭服务,它也会关闭吗?

最佳答案

你可以使用锁或静态变量:

private static boolean isThreadRunning;

然后在您的服务中:

if(isThreadRunning)
   return;

Thread t=new Thread(new Runnable(){

protected void run(){
   isThreadRunning=true;
   while(yourcondition){
     //your thread code...
   }
   isThreadRunning=false;
   //if you want to start another thread after this one is ended, you should post a message to a handler here and it should start another thread like this
}

});

关于android - 服务中只有一个 Thread 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12784024/

相关文章:

android - Android Studio中从URL解析Json文件数据

android - Gradle 无法解析未请求的版本

android - 在 ubuntu 上构建 android ADB 时出错

android - 无法使用 Crashlytics 为 ReactNative 找到有意义的日志

android - Android虚拟设备管理器下缺少"Hardware Section"

android - 类似于 API 8 中的 FLAG_ACTIVITY_CLEAR_TASK 的标志

java - Android Spinner 填充对象

android - 尝试从 Android 中的应用程序上下文访问资源

android - NinePatchDrawable > java.lang.ClassCastException

java - Android 无法在对话框中获取 EditText getText().toString()