【发布时间】:2017-04-24 17:16:48
【问题描述】:
我有一个启用无限条码扫描器的 CustomAsyncTask 类,我在 CustomApplication 中执行它。
不幸的是,CustomAsyncTask::doInBackground 在一段时间(一两分钟)后停止了。
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最多应该使用几秒钟。如果您需要无限期地运行某些东西,请使用服务和线程。如果它仍然崩溃,那么您的代码中有问题。 -
我建议您使用 JobDispatcher 来完成这些作业。
标签: java android multithreading android-asynctask