我正在製作一個更新的android應用程序。爲此,我需要一個簡單的函數,可以下載一個文件並在ProgressDialog中顯示當前的進度。我知道如何下載文件,但我不知道如何顯示當前的進度。我正在使用以下方法下載圖像。Android:顯示進度對話框
public Bitmap DownloadFile(String url){
URL myFileUrl;
Bitmap bitmap=null;
try {
myFileUrl = new URL(imageUrl);
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
bitmap = BitmapFactory.decodeStream((InputStream) new URL(
imageUrl).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap,80 , 80, true);
System.out.println("name of butmap"+bitmap.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
而以下是我的異步任務等級:
public class BackgroundAsyncTask extends AsyncTask<String, Integer, Bitmap> {
int myProgress;
@Override
protected void onPostExecute(Bitmap result) {
dialog.dismiss();
iv.setVisibility(View.VISIBLE);
iv.setImageBitmap(result);
System.out.println("bbbbbbbbb");
System.out.println("post execute");
}
@Override
protected void onPreExecute() {
System.out.println("pre execute");
dialog = ProgressDialog.show(ProfileNormalUserPhotos.this, "Loading...", "Please wait...");
}
@Override
protected Bitmap doInBackground(String...paths) {
System.out.println(imageUrl+" imageurl");
return DownloadFile(imageUrl);
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressBar.setProgress(values[0]);
}
}
和我打電話以下適配器類中的方法:
public class ImageAdapter extends BaseAdapter {
Context mContext;
public String[] stringOnTextView;
public ImageAdapter(Context c) {
mContext = c;
}
public ImageAdapter(Context Context,
String[] stringOnTextView) {
this.mContext=Context;
this.stringOnTextView=stringOnTextView;
}
public int getCount() {
return stringOnTextView.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = null;
if(convertView==null){
try{
{
LayoutInflater li = getLayoutInflater();
v = li.inflate(R.layout.icon, null);
TextView tv = (TextView)v.findViewById(R.id.text);
tv.setText("Profile Image "+(position+1));
iv= (ImageView)v.findViewById(R.id.image);
imageUrl = "http://ondamove.it/English/images/users/";
imageUrl=imageUrl+stringOnTextView[position];
new BackgroundAsyncTask().execute(imageUrl);
}
}catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
else
{
try{
v = convertView;}
catch(Exception e){
System.out.println(e);
}
}
return v;
}
}
我需要下載9倍的圖像,但問題我面對的是它只顯示最後的圖像和進度對話框進入無限循環。
任何人都可以告訴我如何解決thios問題。
感謝
我已經做到了,但我面臨的問題是,進度對話框進入無限循環。 – ekjyot
爲什麼無限?只要檢查是否(dialog.isShowing()){dialog.dismiss(); }裏面的onPostExecute() –
是的,它是在onPostExecute()方法 – ekjyot