使用Android中的Async Task下载并查看内部存储中的Pdf

时间:2019-05-10 11:54:27

标签: android android-asynctask

我正在尝试使用AsyncTask以编程方式从服务器下载和读取pdf,但是没有任何反应。我还有一个seekBar,它会显示下载进度。

我在哪里弄错了?

private void initSeekBar() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
               int val = (progress * (seekBar.getWidth() - 3
               * seekBar.getThumbOffset())) / seekBar.getMax();
               mProgressText.setText("" + progress);
               mProgressText.setX(seekBar.getX() + val + seekBar.getThumbOffset() / 2);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

下载文件

private void downloadFile(final String fileName){
    new AsyncTask<Void, Integer, Boolean>() {
        @Override
        protected Boolean doInBackground(Void... params) {
            return downloadFile();
        }
        @Nullable
        private Boolean downloadFile(){
            try {
                File file = getFileStreamPath(fileName);
                if (file.exists()) {
                    downloadButton.setText("Start Reading");
                    return true;
                }
                try {
                    seekBar.setVisibility(View.VISIBLE);
                    mProgressText.setVisibility(View.VISIBLE);
                    FileOutputStream fileOutputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
                    URL url = new URL(document);
                    URLConnection urlConnection = url.openConnection();
                    int contentLength = urlConnection.getContentLength();
                    InputStream inputStream = new BufferedInputStream(url.openStream());
                    byte data[] = new byte[contentLength];
                    long total = 0;
                    int count;
                    while ((count = inputStream.read(data)) != -1) {
                        total += count;
                        publishProgress((int) ((total * 100) / contentLength));
                        fileOutputStream.write(data, 0, count);

                    }
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    inputStream.close();
                    return true;
                } catch (final Exception e) {
                    e.printStackTrace();
                    return false; //swallow a 404
                }
            }catch (Exception e){
                  e.printStackTrace();
                }
                return false;

            }

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

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if(aBoolean){
                downloadButton.setText("Start Reading");
            } else {
                Toast.makeText(BookDetailsActivity.this, "Download error", Toast.LENGTH_SHORT).show();
                downloadButton.setText("Download");
            }
            seekBar.setVisibility(View.GONE);
            mProgressText.setVisibility(View.GONE);
        }
    };

}

2 个答案:

答案 0 :(得分:0)

使用此代码可能会对您有所帮助。 我正在创建一个从服务器下载pdf文件的一键单击事件。

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class DownloadActivity extends Activity {

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


    public void download(View v)
    {
        new DownloadFile().execute("your url", "save file name .pdf extenstion"); 
    }

    public void view(View v)
    {
        File pdfFile = new File(Environment.getExternalStorageDirectory() + "/test/" + "demo.pdf");  // -> filename = demo.pdf
        Uri path = Uri.fromFile(pdfFile);
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try{
            startActivity(pdfIntent);
        }catch(ActivityNotFoundException e){
            Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
        }
    }

    private class DownloadFile extends AsyncTask<String, Void, Void>{

        @Override
        protected Void doInBackground(String... strings) {
            String fileUrl = strings[0];   
            String fileName = strings[1];
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "test");
            folder.mkdir();

            File pdfFile = new File(folder, fileName);

            try{
                pdfFile.createNewFile();
            }catch (IOException e){
                e.printStackTrace();
            }
            FileDownloader.downloadFile(fileUrl, pdfFile);
            return null;
        }
    }


}

用于下载pdf文件的FileDownloader类

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileDownloader {
    private static final int  MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory){
        try {

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            //urlConnection.setRequestMethod("GET");
            //urlConnection.setDoOutput(true);
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while((bufferLength = inputStream.read(buffer))>0 ){
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

最后,将此权限添加到清单文件中。

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

感谢...编码愉快...

答案 1 :(得分:0)

最后,我找到了解决我问题的方法。我不得不打这条线,

async Task<TResult[]> WhenSome<TResult>(int atLeast, List<Task<TResult>> tasks)
{
    List<Task<TResult>> completedTasks = new List<System.Threading.Tasks.Task<TResult>>();
    int completed = 0;
    List<Exception> exceptions = new List<Exception>();

    while (completed < atLeast && tasks.Any()) {
        var completedTask = await Task.WhenAny(tasks);
        tasks.Remove(completedTask);

        if (completedTask.IsCanceled)
        {
            continue;
        }

        if (completedTask.IsFaulted)
        {
            exceptions.Add(completedTask.Exception);
            continue;
        }

        completed++;
        completedTasks.Add(completedTask);
    }

    if (completed >= atLeast)
    {
        return completedTasks.Select(t => t.Result).ToArray();
    }

    throw new AggregateException(exceptions).Flatten();
}

这是完整的代码:

asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

下载文件

 private void initSeekBar() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
               int val = (progress * (seekBar.getWidth() - 3
               * seekBar.getThumbOffset())) / seekBar.getMax();
               mProgressText.setText("" + progress);
               mProgressText.setX(seekBar.getX() + val + seekBar.getThumbOffset() / 2);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }