Android Async - 文件下载后解压缩

时间:2014-07-28 00:08:48

标签: android asynchronous

我正在尝试在我的活动中创建一个方法,将下载的文件解压缩到某个目录。我尝试了几种不同的方式并没有太多运气。我已经看到有些人使用一个单独的类来完成这个任务,我想避免这样做,但如果这是我唯一的选择那么我会这样做。这是我的活动:

public class lava_parkour extends Activity  {

public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lava_parkour);
     startBtn = (Button)findViewById(R.id.button1);
        startBtn.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                startDownload(v);
            } }); 

    }
    private void startDownload(View v) {
        String url = "https://www.dropbox.com/s/lxnizie52efq3e8/lava%20parkour.zip?
dl=1"; 
        new DownloadFileAsync().execute(url);

    }


    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading...");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    }

class DownloadFileAsync extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }



    @Override
    protected String doInBackground(String... aurl) {
        int count;

    try {

    URL url = new URL(aurl[0]);
    URLConnection conexion = url.openConnection();
    conexion.connect();

    int lenghtOfFile = conexion.getContentLength();
    Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

    InputStream input = new BufferedInputStream(url.openStream());
    OutputStream output = new  
FileOutputStream("/sdcard/games/com.mojang/lava_parkour.zip");



    byte data[] = new byte[1024];

    long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            publishProgress(""+(int)((total*100)/lenghtOfFile));
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
    } catch (Exception e) {}
    return null;

    }
    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }


    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        Toast.makeText(lava_parkour.this, "Process completed! THis map has been added  
   to your game!", Toast.LENGTH_LONG).show();
    }
}

} 

感谢任何帮助!

0 个答案:

没有答案