我的应用程序有一个下载功能花一些时间下载图像,我试图在图像下载时添加ProgressDialog
。 ProgressDialog
永远不会出现请帮帮我
这是我保存图片的代码:
private String saveImage(Bitmap image) {
ProgressDialog pd = new ProgressDialog(Pop.this);
pd.setMessage("Downloading ...");
pd.show();
String savedImagePath = null;
String imageFileName = "vapor"+System.currentTimeMillis()+ ".png";
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/vaporwave");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
// Add the image to the system gallery
galleryAddPic(savedImagePath);
Toast.makeText(Pop.this, "IMAGE SAVED", Toast.LENGTH_LONG).show();
pd.dismiss();
}
return savedImagePath;
}
答案 0 :(得分:0)
你应该使用像AsyncTask
那样的后台任务,你不应该在你的UI线程上做复杂的任务。(否则你的UI会运气直到完成任务,所以你的progressDialog
永远不会显示)
您可以阅读有关AsyncTask Here
的信息例如在async中:
1)在onPreExecute
2)并在onPostExecute
3)并在doInBackground
中完成工作(保存图片)(此方法中的返回类型将传递给onPostExecute
)
public class saveImage extends AsyncTask<Bitmap,Void,String>{
ProgressDialog pd;
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(Pop.this);
pd.setMessage("Downloading ...");
pd.show();
}
@Override
protected String doInBackground(Bitmap... params) {
Bitmap image = params[0];
String savedImagePath = null;
String imageFileName = "vapor"+System.currentTimeMillis()+ ".png";
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/vaporwave");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
// Add the image to the system gallery
galleryAddPic(savedImagePath);
Toast.makeText(Pop.this, "IMAGE SAVED", Toast.LENGTH_LONG).show();
pd.dismiss();
}
return savedImagePath;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//s is your savedImagePath
pd.dismiss();
}
}
你可以像这样调用这个任务:
new saveImage().execute(yourBitmap);