我在服务中初始化新的线程,但是当我开始服务时,新的线程被制作并且它使我的应用程序崩溃,因为我在其中使用相机。 如何使它成为该线程的一个实例?
线程何时关闭?如果我在我做的地方关闭服务,它也会被关闭?
答案 0 :(得分:4)
你可以使用锁或静态变量:
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
}
});
答案 1 :(得分:0)
您也可以使用Handler
类来实现此目标,这是Google在线程操作中推荐的。下面的代码显示了如何在Service
中使用它的通用示例。
public class MyService extends Service{
private final Handler handler = new Handler();
private final static int RUNABLE_WHAT=6558057;
private final static int PEROID=6*1000;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!handler.hasMessages(RUNABLE_WHAT))
{
handler.sendMessageDelayed(new Worker().extractMessage(), PEROID);
}
return START_STICKY;
}
private class Worker implements Runnable{
@Override
public void run() {
//DO WORK HERE
handler.sendMessageDelayed(new Worker().extractMessage(), PEROID);
}
private Message extractMessage()
{
Message message = Message.obtain(handler, this);
message.what=RUNABLE_WHAT;
return message;
}
}
}