1

您如何根据以下代码实现进度下载对话框?我的代码从特定 URL 下载图像,然后将图像文件保存到 SD 卡中并将图像设置为墙纸。当用户触摸选项菜单按钮 setwallpaper() 时,我想显示一个进度下载对话框。

public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.set_wallpaper:
                SetWallpaper(image_url);
                return true;
            default:
                return false;
        }
    }



public void SetWallpaper(String image_url)
        {   
        URL myFileUrl = null;
            try
        {   
                myFileUrl = new URL(image_url); 
        }
            catch (MalformedURLException e)
            {      
                e.printStackTrace();  
            }   
            Bitmap bmImg = null;
            try {  
                HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();   
                conn.setDoInput(true);   
                conn.connect();     
                //int length = conn.getContentLength(); 
            InputStream is = conn.getInputStream();
            bmImg = BitmapFactory.decodeStream(is); 
            }
                catch (IOException e)
                {       
                    e.printStackTrace();  
                }   
        try {       

            String path = myFileUrl.getPath();
            String idStr = path.substring(path.lastIndexOf('/') + 1);
            File filepath = Environment.getExternalStorageDirectory();
            File dir = new File (filepath.getAbsolutePath() + "/Wallpaper/");
                dir.mkdirs();
                String fileName = idStr;
                File file = new File(dir, fileName);
                FileOutputStream fos = new FileOutputStream(file);

                bmImg.compress(CompressFormat.JPEG, 75, fos);   
                fos.flush();    
                fos.close();       

                WallpaperManager wpm = WallpaperManager.getInstance(getBaseContext());
                wpm.setBitmap(bmImg);

        }
        catch (Exception e){


            e.printStackTrace();  
        }
        }

我的尝试:捕获异常。请参考以下代码

    public class SingleMenuItemActivity  extends Activity {

    // XML node keys
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";  
static final String KEY_THUMB_URL = "thumb_url";
ProgressBar progressbar;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.single_list_item);

        ImageView image = (ImageView) findViewById(R.id.single_image);
        Intent in = getIntent();

        String image_url = in.getStringExtra(KEY_THUMB_URL);


        ImageLoader imgLoader = new ImageLoader(getApplicationContext());


        imgLoader.DisplayImage(image_url, image);

        String title = in.getStringExtra(KEY_TITLE);
        String artist = in.getStringExtra(KEY_ARTIST);


        TextView lblName = (TextView) findViewById(R.id.name_title);
        TextView lblCost = (TextView) findViewById(R.id.name_artist);
        progressbar = (ProgressBar) findViewById(R.id.loadingBar);

        lblName.setText(title);
        lblCost.setText(artist);


    }

    public class loadImageTask extends AsyncTask<String, Void, Void>
    {
        //Drawable imgLoad;
        URL myFileUrl = null;
        Bitmap bmImg = null;
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            Intent in = getIntent();
        String image_url = in.getStringExtra(KEY_THUMB_URL);
        try {
            myFileUrl = new URL(image_url);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        super.onPreExecute();

        progressbar.setVisibility(View.VISIBLE);
    }

        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub

            try {  
                HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();   
                conn.setDoInput(true);   
                conn.connect();     
                InputStream is = conn.getInputStream();
                bmImg = BitmapFactory.decodeStream(is); 
            }
            catch (IOException e)
            {       
                e.printStackTrace();  
            }
            try {       

                String path = myFileUrl.getPath();
                String idStr = path.substring(path.lastIndexOf('/') + 1);
            File filepath = Environment.getExternalStorageDirectory();
            File dir = new File (filepath.getAbsolutePath() + "/Wallpaper/");
                dir.mkdirs();
                String fileName = idStr;
                File file = new File(dir, fileName);
                FileOutputStream fos = new FileOutputStream(file);
                bmImg.compress(CompressFormat.JPEG, 75, fos);   
                fos.flush();    
                fos.close();       
            }
            catch (Exception e)
                    {
                        e.printStackTrace();  
                    }
            return null;   
        }
        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);

            if(progressbar.isShown())
            {
                progressbar.setVisibility(View.GONE);

            }
        }
    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent in = getIntent();
        String image_url = in.getStringExtra(KEY_THUMB_URL);
        switch (item.getItemId()) {
            case R.id.save_image:
                new loadImageTask().execute(image_url);

                return true;
            default:
                return false;
        }
4

2 回答 2

1

在这里,您可以使用 AsyncTask 来显示进度条/对话框。

Show the progress bar visible inside the onPreExecute() method. And performs the image loading operations inside the doInBackground() method. Once this operation is done, we will make progress bar invisible and make imageview visible with that loaded image inside the onPostExecute() method.

For more information check this LINK

于 2012-08-17T04:10:39.140 回答
0

尝试使用这个

final ProgressDialog dialog = ProgressDialog.show(
            YourACtivity.this, "", "Loading...please wait");

    new Thread(new Runnable() {
        @Override
        public void run() {
        SetWallpaper(image_url);
                  if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
        }
    }).start();

}

代替

SetWallpaper(image_url);

在 onOptionsItemSelected(MenuItem 项)

然后使用 Handlers 处理http://developer.android.com/reference/android/os/Handler.html

于 2012-08-17T03:17:17.620 回答