如何在上面的代码中设置进度条?

时间:2014-08-05 10:10:07

标签: android

我是Android的新手,我正在制作一个应用程序从本地服务器下载文件,我差点完成。但现在我想在此代码中添加进度条,我正在尝试这样做。谁能帮我吗。如果你不能留下像语法错误和其他

的其他评论,请帮助我
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.support.v7.app.ActionBarActivity;
import android.widget.Button;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;  

public class MainActivity extends ActionBarActivity 
{
Button b1;
String FileDownloadPath="http://192.168.1.25/dinesh/di.mp3";
//String FileSavePath="/dinesh2/lecture3.pdf";
//String DownloadUrl = "http://myexample.com/android/";
String fileName = "di.mp3";
//myFile = new File(path,"/mysdfile.xml");
ProgressDialog dialog=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b1=(Button)findViewById(R.id.button1);


    b1.setOnClickListener(new OnClickListener(){
        public void onClick(View arg0)
        {

        dialog=ProgressDialog.show(MainActivity.this,"", "downloading",true);
        new Thread(new Runnable()
        {
            public void run()
            {
                downlaodfile(FileDownloadPath,fileName);
            }


    }).start();

}
});


}
public void downlaodfile(String FileDownloadPath, String fileName) {
    try {
        File root = android.os.Environment.getExternalStorageDirectory();
        File dir = new File(root.getAbsolutePath() + "/sdcard/myclock/databases");
        if(dir.exists() == false){
             dir.mkdirs();  
        }

        URL url = new URL("http://192.168.1.25/dinesh/di.mp3");
        File file = new File(dir,fileName);

        long startTime = System.currentTimeMillis();
        Log.d("DownloadManager" , "download url:" +url);
        Log.d("DownloadManager" , "download file name:" + fileName);

        URLConnection uconn = url.openConnection();
        /* uconn.setReadTimeout(TIMEOUT_CONNECTION);
        uconn.setConnectTimeout(TIMEOUT_SOCKET);*/

        InputStream is = uconn.getInputStream();
        BufferedInputStream bufferinstream = new BufferedInputStream(is);

        ByteArrayBuffer baf = new ByteArrayBuffer(5000);
        int current = 0;
        while((current = bufferinstream.read()) != -1){
            baf.append((byte) current);
        }

        FileOutputStream fos = new FileOutputStream( file);
        fos.write(baf.toByteArray());
        fos.flush();
        fos.close();
        Log.d("DownloadManager" , "download ready in" + ((System.currentTimeMillis() - startTime)/1000) + "sec");
        int dotindex = fileName.lastIndexOf('.');
        if(dotindex>=0){
            fileName = fileName.substring(0,dotindex);

    }
    }

    catch(IOException e) {
        Log.d("DownloadManager" , "Error:" + e);
    }
    catch(Exception e )
    {
        e.printStackTrace();
    }



}



private void hideProgressIndicator() {
    // TODO Auto-generated method stub
    runOnUiThread(new Runnable(){
        public void run()
        {
            dialog.dismiss();

        }

    });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


}

1 个答案:

答案 0 :(得分:0)

您应该使用AsyncTask<...>进行下载,并使用ProgressDialog

    private class ClassName extends AsyncTask<String, Void, String>
        {
            ProgressDialog progressDialog; 

            @Override
            protected void onPreExecute() 
            {
                progressDialog = ProgressDialog.show(context, "Downloading", "Please Wait...");
            }

            @Override
            protected String doInBackground(String... params) 
            {
                //Your downloading code here
            }

            @Override
            protected void onPostExecute(String result) 
            {
                super.onPostExecute(result);

                progressDialog.dismiss();

                //dismiss the progress dialog in onPost and do remaining stuff after downloading....
            }
}

希望这会对你有所帮助......