简体   繁体   中英

Progress bar for asynctask downloading

在此处输入图片说明

I just want to make an app to download multiple files sequentially. But when I click download button, the progress bar doesn't move and logcat shows:

05-11 18:46:26.227 2653-2899/shiweichen22gmail.q4 E/Error: /storage/emulated/0/Q4.txt: open failed: EACCES (Permission denied)

I already have permission in the manifest.xml

mainactivity.XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="shiweichen22gmail.q4.MainActivity"
tools:showIn="@layout/activity_main"
android:weightSum="1">


<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Large Text"
    android:id="@+id/textView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_weight="0.17" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Download"
    android:id="@+id/button"
    android:layout_below="@+id/textView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="61dp"
    android:layout_gravity="center_vertical" />
</LinearLayout>

Mainactivity.java

 package shiweichen22gmail.q4;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;


public class MainActivity extends AppCompatActivity {

private Button startBtn;
private ProgressDialog mProgressDialog;
String[] URL = {"https://www.dropbox.com/s/gjq0ivomwti4vmw/1.txt?dl=0",
       };
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startBtn = (Button)findViewById(R.id.button);
    startBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          new DownloadFile().execute(URL);
        }
    });
}
private class DownloadFile  extends AsyncTask<String, Integer, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create progress dialog
        mProgressDialog = new ProgressDialog(MainActivity.this);
        // Set your progress dialog Title
        mProgressDialog.setTitle("Downloading");
        // Set your progress dialog Message
        mProgressDialog.setMessage("Downloading, Please Wait!");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        // Show progress dialog
        mProgressDialog.show();
    }
    @Override
    protected String doInBackground(String... Url) {
        try {
            URL url = new URL(Url[0]);
            URLConnection connection = url.openConnection();
            connection.connect();
            // Detect the file lenghth
            int fileLength = connection.getContentLength();
            // Locate storage location
            String filepath = Environment.getExternalStorageDirectory()
                    .getPath();
            // Download the file
            InputStream input = new BufferedInputStream(url.openStream());
            // Save the downloaded file
            OutputStream output = new FileOutputStream(filepath+ "/"
                    + "Q4.txt");
            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                // Publish the progress
                publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
            // Error Log
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        // Update the progress dialog
        mProgressDialog.setProgress(progress[0]);
        // Dismiss the progress dialog
        //mProgressDialog.dismiss();
    }
}
}

Mainfest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="shiweichen22gmail.q4">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>

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

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

</manifest>

Override the onPostExecute() and set mProgressDialog.dismiss(); like below :

private class DownloadFile  extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
    super.onPreExecute();
    // Create progress dialog
    mProgressDialog = new ProgressDialog(MainActivity.this);
    // Set your progress dialog Title
    mProgressDialog.setTitle("Downloading");
    // Set your progress dialog Message
    mProgressDialog.setMessage("Downloading, Please Wait!");
    mProgressDialog.setIndeterminate(false);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    // Show progress dialog
    mProgressDialog.show();
}
@Override
protected String doInBackground(String... Url) {
    try {
        URL url = new URL(Url[0]);
        URLConnection connection = url.openConnection();
        connection.connect();
        // Detect the file lenghth
        int fileLength = connection.getContentLength();
        // Locate storage location
        String filepath = Environment.getExternalStorageDirectory()
                .getPath();
        // Download the file
        InputStream input = new BufferedInputStream(url.openStream());
        // Save the downloaded file
        OutputStream output = new FileOutputStream(filepath+ "/"
                + "Q4.txt");
        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            // Publish the progress
            publishProgress((int) (total * 100 / fileLength));
            output.write(data, 0, count);
        }
        output.flush();
        output.close();
        input.close();
    } catch (Exception e) {
        // Error Log
        Log.e("Error", e.getMessage());
        e.printStackTrace();
    }
    return null;
}
@Override
 protected void onPostExecute(Void args) {


        // Close the progressdialog
        mProgressDialog.dismiss();
    }

if you are running your app on marshmallow you need to ask for runtime permissions. here is more information on Runtime Permissions http://developer.android.com/training/permissions/requesting.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM