按下按钮后下载未执行

时间:2015-12-03 10:26:35

标签: android

我正在测试一个按钮点击下载文件的应用。但是当点击按钮时没有任何反应。出现对话框,并在几分之一秒内消失。不知道出了什么问题 这是我的代码

mainactivity

public class MainActivity extends Activity 
{
public static final int DIALOG_DOWNLOAD_PROGRESS = 0; 
private Button startBtn;
    private ProgressDialog mProgressDialog;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    startBtn = (Button) findViewById(R.id.mainButton);

    startBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View p1)
            {
                // TODO: Implement this method
                startDownload();
            }

        });
}

private void startDownload()
{ 
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url); 
} 
@Override protected Dialog onCreateDialog(int id)
{
    switch (id)
    {
        case DIALOG_DOWNLOAD_PROGRESS: mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Downloading file..");
        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/some_photo_from_gdansk_poland.jpg");
            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);
    }
    }
 }

Android清单

<?xml version="1.0" encoding="utf-8"?>

uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    


<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

2 个答案:

答案 0 :(得分:0)

Handler handler = new Handler();

    class DownloadFileAsync extends AsyncTask<Void, Integer, String> {
        ProgressDialog progressDialog;
        Context context;
        String downloadUrl;
        // shared preferences
        SharedPreferences sharedPreferences;
        int state;

        public DownloadFileAsync(Context context, String downloadUrl) {
            this.context = context;
            this.downloadUrl = downloadUrl;
        }

        @Override
        protected void onPreExecute() {

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog = new ProgressDialog(context);
                        progressDialog.setMessage("Downloading file. Please wait......");
                        progressDialog.setIndeterminate(false);
                        progressDialog.setMax(100);
                        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        progressDialog.show();
                    }
                });
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressDialog.setProgress(values[0]);
        }

        @Override
        protected String doInBackground(Void... params) {
            int count;
            try {
                URL url = new URL(downloadUrl.toString());
                URLConnection conection = url.openConnection();
                conection.setReadTimeout(5000);
                conection.connect();
                // getting file length
                int lenghtOfFile = conection.getContentLength();
                if (lenghtOfFile > 0) {
                    // input stream to read file - with 8k buffer
                    InputStream input = new BufferedInputStream(url.openStream(), 8192);

                    // Output stream to write file
                    OutputStream output = new FileOutputStream(
                            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                                    + "/data.jpg");
                    byte data[] = new byte[1024];

                    long total = 0;
                    Log.d("lenghtOfFile", "---" + lenghtOfFile);
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        // writing data to file
                        output.write(data, 0, count);
                        // publishing the progress. After this onProgressUpdate
                        // will be called
                        publishProgress((int) ((total * 100) / lenghtOfFile));
                    }

                    // flushing output
                    output.flush();

                    // closing streams
                    output.close();

                    input.close();
                }
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

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

            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
        }

    }

点击按钮,如下所示调用

new DownloadFileAsync(MainActivity.this, url).execute();

它可以工作并在清单

中添加以下权限
<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

答案 1 :(得分:0)

这是工作代码..

for i=$( ...