文件没有下载,并且在android中没有正确显示进度

时间:2016-07-07 18:19:11

标签: android android-asynctask android-external-storage

我编写一个代码来下载带圆圈进度条的文件。但是文件没有下载到外部存储器,进度条不显示任何进度号。 logcat中没有显示错误。我的代码中没有错。帮我解决这个问题。这是我的代码。我在清单文件中添加了所有权限和活动类。提前谢谢。

package com.example.skr.downloader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;



public class DownloaderClass extends Activity {

    EditText txturl;
    int progress=0;
    public ProgressDialog progressDialog;
    public DownloaderClass(){

    }

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

    }

    public void onDownload(View v){
        txturl=(EditText)findViewById(R.id.txtURL);

        progressDialog=new ProgressDialog(DownloaderClass.this);

        final AsyncDownloaderClass asyncDownloaderClass=new AsyncDownloaderClass();
        asyncDownloaderClass.execute("http://pinnest.net/newpinnest/wp-content/uploads/2013/08/1377250577ea43d.jpg");
    }
    class AsyncDownloaderClass extends AsyncTask<String,Integer, String>
    {
        private PowerManager.WakeLock mWakeLock;
        Context context;
        String filename, basename;
        int fileLength;

        DownloaderClass downloaderClass;
        public AsyncDownloaderClass(){

            downloaderClass=new DownloaderClass();
            context=downloaderClass;

            /*PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,getClass().getName());*/
        }
        protected void onPreExecute(){
           // super.onPreExecute();
            progressDialog.setMessage("Downloading....");
            progressDialog.setTitle("Please Wait...");
            progressDialog.setCanceledOnTouchOutside(false);
            //progressDialog.setIndeterminate(false);
            progressDialog.setProgress(progress);
            //progressDialog.setMax(100);
            progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new AsyncDownloaderClass().cancel(true);
                        }
                    }
            );


            //mWakeLock.acquire();
            progressDialog.show();

        }
        @Override
        protected String doInBackground(String... params) {
           //return null;
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(params[0]);

                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                // expect HTTP 200 OK, so we don't mistakenly save error report
                // instead of the file
                Log.v("Do in background","calling.....");
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();
                    }

                input = connection.getInputStream();
                BufferedInputStream bufferedInputStream=new BufferedInputStream(input);

               fileLength = connection.getContentLength();
                filename=url.getPath();
                filename=filename.substring(filename.lastIndexOf('/') + 1);



   output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"download.jpg");

               byte data[] = new byte[1024];
                long total = 0;
                int count=0;

               while ((count = input.read(data)) != -1) {
                    // allow canceling with back button

                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;
                    // publishing the progress....
                    if (fileLength > 0) // only if total length is known
                        publishProgress((int) (total * 100 / fileLength));

                    output.write(data, 0, count);

                }

            } catch (Exception e) {
                return e.toString();
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                    Log.v("Error","Error");
                }

                if (connection != null)
                    connection.disconnect();
            }
            return null;
        }


        protected void onProgressUpdate(Integer... values){
            progressDialog.setProgress(values[0]);
            progressDialog.setMessage("Downloading... " + values[0] + "%");
        }
        protected void onPostExecute(String... result){
            progressDialog.dismiss();
            if (result != null)
                Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
            else
                Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();

        }
    }
}

清单文件

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.skr.downloader">
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>

    <application android:allowBackup="true" android:label="@string/app_name"
        android:icon="@drawable/download" android:supportsRtl="true"
        android:theme="@style/AppTheme"
        >

        <activity android:name="com.example.skr.downloader.LauncherClass">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"></action>
                <category android:name="android.intent.category.LAUNCHER"></category>

            </intent-filter>
        </activity>
        <activity android:name=".DownloaderClass">
            <intent-filter>
                <action android:name="my.android.download"></action>
                <category android:name="android.intent.category.DEFAULT"></category>
            </intent-filter>

        </activity>
    </application>

</manifest>

1 个答案:

答案 0 :(得分:0)

onPostExecute的签名是错误的。改变

protected void onPostExecute(String... result){ 

@Override 
protected void onPostExecute(String result){. 

现在它从未被调用过。并改变

output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"download.jpg");

output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/download.jpg");
相关问题