Android AsycTask跳过帧。不更新用户界面
我正在使用异步任务从服务器下载文件, 在文件下载过程中,我将使用指针显示进度。 在异步任务中,我调用发布进度方法Android AsycTask跳过帧。不更新用户界面,android,android-asynctask,Android,Android Asynctask,我正在使用异步任务从服务器下载文件, 在文件下载过程中,我将使用指针显示进度。 在异步任务中,我调用发布进度方法 while (true) { final int read = inputStream.read(readArray); if (read <= 0) { break;
while (true) {
final int read = inputStream.read(readArray);
if (read <= 0) {
break;
}
totalRead+= read;
this.publishProgress(String.valueOf(100L * totalRead/ contentLength));
}
但它不是每次都执行。帧被跳过,跳过警告即将到来
跳过的100帧应用程序可能在其主应用程序上做了太多工作
线
如何解决此问题,使其不会错过GUI中的更新 onProgressUpdate方法中的所有内容都在主线程上。此部分花费的时间太长:
Bitmap.createBitmap(
this.pointerBitmap,
0,
0,
this.pointerBitmap.getWidth(),
this.pointerBitmap.getHeight(),
matrix,
true)
);
<>避免在主线程上进行像这样的昂贵操作,而应考虑在异步任务中创建位图。考虑这样的事情:
private class AsyncTaskExample extends AsyncTask<Void, Bitmap, Void>{
@Override
protected void onProgressUpdate(Bitmap... values) {
super.onProgressUpdate(values);
if(values.length >0){
needleImage.setImageBitmap(values[0]);
}
}
@Override
protected Void doInBackground(Void... params) {
//do some stuff
final Matrix matrix = new Matrix();
while (true) {
final int read = inputStream.read(readArray);
if (read <= 0) {
break;
}
totalRead+= read;
matrix.reset();
matrix.postRotate(100L * totalRead/ contentLength);
publishProgress(
Bitmap.createBitmap(
this.pointerBitmap, // keep a copy of the bitmap within the asynctask so you can access it
0,
0,
this.pointerBitmap.getWidth(),
this.pointerBitmap.getHeight(),
matrix,
true
)
);
}
// do some stuff
return null
}
}
}
私有类AsyncTaskExample扩展了AsyncTask{
@凌驾
受保护的void onProgressUpdate(位图…值){
super.onProgressUpdate(值);
如果(value.length>0){
setImageBitmap(值[0]);
}
}
@凌驾
受保护的Void doInBackground(Void…参数){
//做点什么
最终矩阵=新矩阵();
while(true){
final int read=inputStream.read(readArray);
如果(读取您不应该在每次显示进度时都创建新位图。请尝试旋转ImageView。您不能在doinBackground中的AsycTask期间更改gui。您必须在doIn后台之前启动程序。在onPreExecute()上显示它,在onPostExecute()上关闭它方法。@Cüneyt我只需要在下载过程中显示进度(doInBackground)。:)谢谢joe。我将尝试实施您的建议。如果可能,请提供任何链接以继续,或者提供任何其他替代方案,以便我可以使用handler/thread更新UI(如果可能)。我建议查看为您的针图像创建自定义视图。您的目标是仅加载两个位图:背景和针。您的自定义视图将绘制背景,旋转画布,绘制针,并在其onDraw()方法中恢复画布
private class AsyncTaskExample extends AsyncTask<Void, Bitmap, Void>{
@Override
protected void onProgressUpdate(Bitmap... values) {
super.onProgressUpdate(values);
if(values.length >0){
needleImage.setImageBitmap(values[0]);
}
}
@Override
protected Void doInBackground(Void... params) {
//do some stuff
final Matrix matrix = new Matrix();
while (true) {
final int read = inputStream.read(readArray);
if (read <= 0) {
break;
}
totalRead+= read;
matrix.reset();
matrix.postRotate(100L * totalRead/ contentLength);
publishProgress(
Bitmap.createBitmap(
this.pointerBitmap, // keep a copy of the bitmap within the asynctask so you can access it
0,
0,
this.pointerBitmap.getWidth(),
this.pointerBitmap.getHeight(),
matrix,
true
)
);
}
// do some stuff
return null
}
}
}