AsyncTask在Android中未按预期工作


GetImages getImages = new GetImages();
getImages.execute(keys); 

private class GetImages extends AsyncTask(String, Void, Void){

@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(String... keys) {
for(String key : keys){
StorageReference referenceImage = FirebaseStorage.getInstance().getReference().child("images/"+key);
final long ONE_MB = 1024*1024;
referenceImage.getBytes(ONE_MB).addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(byte[] bytes) {
Toast.makeText(getApplicationContext(),"Success to Load Bitmap ....",Toast.LENGTH_LONG).show();
Bitmap bm = BitmapFactory.decodeByteArray(bytes,0,bytes.length);
}
});
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
Toast.makeText(getApplicationContext(),"Completed  All   Tasks ............",Toast.LENGTH_LONG).show();
}
}
}

该代码的问题在于AsyncTask在完成doInBackGround()之前执行onPostExecute()已完成所有任务toast显示在成功加载位图toast之前。我不明白问题出在哪里。

Firebase方法referenceImage.getBytes本身是异步的,您不需要将其放入AsyncTask中。对于在获取图像后显示Toast,您可以执行以下操作:

referenceImage.getBytes(ONE_MB).addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(byte[] bytes) {
Toast.makeText(getApplicationContext(),"Success to Load 
Bitmap....",Toast.LENGTH_LONG).show();
Bitmap bm = BitmapFactory.decodeByteArray(bytes,0,bytes.length);
Toast.makeText(getApplicationContext(),"Completed  All Tasks 
............",Toast.LENGTH_LONG).show();
}
});
GetImages getImages = new GetImages();
getImages.execute(key); 

密钥必须在GetImages类中初始化

protected void onPostExecute(Void aVoid) {
Toast.makeText(getApplicationContext(),"Completed  All   Task .......",Toast.LENGTH_LONG).show();
}

方法在doinbackground完成后运行,您需要返回标记完成方法的标志或数据。不返回空

相关内容

  • 没有找到相关文章

最新更新