进度完成对话窗口Android

时间:2014-07-14 13:44:53

标签: android

因此,在我的代码中,我设置了这样,当有人按下button1时,它将开始下载,并出现一个进度条并向他们显示下载。我的问题是,文件太小,从0-100%这么快你甚至可以注意到它,所以我想在下载完成后弹出一个对话框。继承我的代码:

public class v090 extends Activity {

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

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.v090);
    startBtn = (Button)findViewById(R.id.button1);
    startBtn.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            startDownload();
        } }); 
}

private void startDownload() {
    String url = "https://docs.google.com/uc?   
authuser=0&id=0B6ocq4LWhNJkRlpXelpheGtnZUE&export=download";
    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/Android/data/com.snowbound.pockettool.free/Patches/shadermod.mod"    );



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);
}
}
} 

1 个答案:

答案 0 :(得分:0)

我强烈反对弹出对话框,这是一种不好的做法,因为它会破坏与您的应用的互动并迫使用户进行确认。只有在绝对必要时才这样做。

如果您要完成比进度条更多的确认,请使用Toast代替。在onPostExecute的{​​{1}} - 方法中执行此操作是安全的,因为在后台任务完成后,UI线程中发生了任何事情:

AsyncTask

PS:按照惯例,Java中类名的第一个字母通常是大写的。