[英]AsyncTask stops after some time
我有一个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。 AsyncTasks仅设计为与较短的后台任务一起运行。 请记住,在Service
运行的任何内容都将在主线程上执行,因此您应该在Service
使用后台线程。
您能否说出AsyncTask或IntentService为何停止? 使用IntentService
并使用while(true)循环,它应无限期运行,除非应用由于某种原因被关闭。
编辑-
您需要执行此操作以防止循环阻塞主线程-
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
// your code here
}
}
});
t.start();
}
我不知道您的服务为何停止。 您需要查看Logcat的输出。 将过滤器设置为“错误”,您应该崩溃了。
是的,这种类型的东西有一个优雅的解决方案。 使用服务。 特别地,JobScheduler api旨在处理这种事情。 如您所说,使用此功能的原因是您的任务运行时间长,并且您不必管理即将死去的任务。 此外,JobScheduler旨在处理OS的副作用。 我假设您希望您的作业运行,但是允许该应用执行其正常的操作集。 尽管需要注意的是,尽管该API在考虑电池电量,所使用的OS资源,WiFi连接等因素方面很明智,但是可以推迟这些工作。
官方文档在这里https://developer.android.com/reference/android/app/job/JobScheduler.html
有关如何使用它的示例,请参见https://code.tutsplus.com/tutorials/using-the-jobscheduler-api-on-android-lollipop--cms-23562
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.