簡體   English   中英

使用AsyncTask創建音頻下載器方法

[英]Create Audio Downloader method with AsyncTask

我最近用Asynctask創建了一個ImageDownloader方法,現在我需要與在當前項目中下載音頻完全相同的方法。請您幫我編輯此方法!

(如果我在這里有一些錯誤,請糾正我,因為我是Android新手)

這是我的ImageDownloader AsynkTask:

    public class ImageDownloader extends AsyncTask<String, String, String> {

     private PowerManager.WakeLock mWakeLock;

    @Override
    protected void onPreExecute() {
        super.onPreExecute(); 

        PowerManager pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
             getClass().getName());
        mWakeLock.acquire();
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setTitle("Downloading...");
        mProgressDialog.setMessage("Please wait while your file is downloading...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgress(100);



        mProgressDialog.show();
    }

    @Override
    protected String doInBackground(String... image_urls) {
         int count = 0;
        try {  

             URL url = new URL(image_urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
            conn.setDoInput(true);   
            conn.connect();     
            InputStream is = conn.getInputStream();
            bmImg = BitmapFactory.decodeStream(is);

            while(count != 100){
                publishProgress(""+count);
                count +=5;
            }
        }
        catch (IOException e)
        {       
            e.printStackTrace();  
        }

        return null;   
    }

    @Override
    protected void onProgressUpdate(String... progress) {
        Log.v("count",progress[0]);
        mProgressDialog.setProgress(Integer.parseInt(progress[0]));
   }     

@Override       
protected void onPostExecute(String args) {

             mWakeLock.release();      
             File showPathInToast;
             File filename;
             try {
                 String path = Environment.getExternalStorageDirectory().toString();
                 Log.i("in save()", "after mkdir");
                 new File(path + "/Dastak/News").mkdirs();

                 String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                 String imageFileName = timeStamp;

                 filename = new File(path + "/Dastak/News/"+ imageFileName +".jpg");
                 showPathInToast = new File(path + "/Dastak/News/");

                 Log.i("in save()", "after file");
                 FileOutputStream out = new FileOutputStream(filename);
                 Log.i("in save()", "after outputstream");
                 bmImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
                 out.flush();
                 out.close();
                 Log.i("in save()", "after outputstream closed");
                 // MediaStore.Images.Media.insertImage(getActivity().getContentResolver(),
                 //filename.getAbsolutePath(), filename.getName(),filename.getName());

                 Toast.makeText(getActivity().getApplicationContext(),
                         "File has been saved to " + showPathInToast , Toast.LENGTH_LONG).show();
             } catch (Exception e) {
                 e.printStackTrace();
             }

             mProgressDialog.dismiss();
        }
      }

這是一個簡單的AsyncTask。 您可以在構造函數中指定目標File,並在調用execute時指定url。 它只是讀取InputStream,直到不返回任何內容,然后使用FileOutputStream直接寫入目標File。

private class FileDownloadTask extends AsyncTask<String, Void, Void> {

    File destination;

    public FileDownloadTask(File destination) {
        this.destination = destination;
    }

    @Override
    protected Void doInBackground(String... urls) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urls[0]);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();

            if(!destination.exists()) {
                if(!destination.mkdirs()) {
                    return null;
                }
            }

            InputStream is = conn.getInputStream();
            FileOutputStream fos = new FileOutputStream(destination);

            byte[] bytes = new byte[1024];

            while ((is.read(bytes) >= 0)) {
                fos.write(bytes);
            }

            fos.flush();
            fos.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }
}

顯然,您可以再次添加ProgressDialog邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM