我有一个CustomAsyncTask类,它启用无限条形码扫描器,并在CustomApplication中执行它。
不幸的是CustomAsyncTask::doInBackground
在一段时间后(一两分钟)停止。AsyncTask在一段时间后停止
private class ScanAsync extends AsyncTask<Void, String, Void>
{
boolean blocked = false;
@Override
protected Void doInBackground(Void... params)
{
while(true)
{
if (!blocked)
{
String received = GlobalAccess.scan.scan(500);
if (received != null && !received.isEmpty())
{
blocked = true;
publishProgress(received);
}
}
else
{
try
{
Thread.sleep(500);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}
}
@Override
protected void onProgressUpdate(String... values)
{
super.onProgressUpdate(values);
//TODO: something with received value
blocked = false;
}
}
我需要这个后台任务永远在。有没有什么好的解决方案?我试过IntentService,但结果是一样的 - 一段时间后它停止工作。
编辑
我创造了这个服务,虽然它挡住了我的主线程,但它应该在后台工作的权利?另外,如果我在if(!blocked)
上放置了一个断点并按F9,它可以正常工作(扫描部分),但是如果我删除断点并让它运行 - 几秒钟后它就会关闭(扫描仪),但如果我再次放置断点 - 再次(原文如此!)。
public class ScanService extends Service
{
boolean blocked = false;
public ScanService()
{
}
@Nullable
@Override
public IBinder onBind(Intent intent)
{
return null;
// TODO: Return the communication channel to the service.
//throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
while(true)
{
if (!blocked)
{
String received = GlobalAccess.scan.scan(500);
if (received != null && !received.isEmpty())
{
//blocked = true;
}
}
else
{
try
{
Thread.sleep(500);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}
}
}
安置自己的堆栈跟踪中如何使用它的一个例子。 'AsyncTask'应该最多使用几秒钟。如果你需要某些东西无限期地运行,那么使用一个服务和一个线程。如果它仍然崩溃,那么代码中存在问题。 – Pztar
我建议你为这些工作使用JobDispatcher。 – HaroldSer