Android Asynctask在销毁活动后获得后台的最后进展

时间:2018-03-26 10:01:24

标签: android android-asynctask download

我现在要做的是从包含大约875个文件的URL循环下载pdf。

我已经通过使用Asynctask并更新进度中的进度对话框也完成了一切工作正常,但我遇到的问题是当用户点击我的DOWNLOAD IN BACKGROUND按钮时,下载仍在继续我想再次重新开放这项活动。但是显示给用户的文件的进度和名称不再显示。

我知道当我们开始新的活动时,它会忽略我们上一个Asynctask的后台运行过程,那么我们怎么能解决这个问题呢? (对不起我的英语,这是我第一次通过StackOverflow)

my code is similar to this

我的代码示例:

class DownloadFileFromURL extends AsyncTask<ArrayList<LawDocument>,Integer, String> {

    private boolean running = true;
    Exception error;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if(haveNetworkConnection()){
            showDialog(progress_bar_type);
        }else {
            running = false;
            showdailog();
        }
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        running = false;
    }

    @Override
    protected String doInBackground(ArrayList<LawDocument>[] f_url) {
        ArrayList<LawDocument> passed = f_url[0]; //get passed arraylist
        System.out.println("Data::" + passed.size());
        int count;

        InputStream input = null;
        OutputStream output = null;
        while(!isCancelled()) {
            try {

                for (int i = 0; i < passed.size(); i++) {

                        File file = getBaseContext().getFileStreamPath(passed.get(i).getActualFilename());
                          if (file.exists()){
                                countfile+=1;
                               pDialog.setMessage(" Exist / "+ConstantClass.filecount);
                          }else{
                        Log.d("checkFilecount" + i, "fileName: " + passed.get(i).getFileName());
                        String filename = passed.get(i).getFileName().substring(passed.get(i).getFileName().lastIndexOf("/") + 1);
                        Log.d("checkFile", "name: " + filename);
                        URL url = new URL(passed.get(i).getFileName());
                        System.out.println("Data::" + passed.get(i).getFileName());
                        URLConnection conection = url.openConnection();
                        conection.connect();
                        // getting file length
                        int lenghtOfFile = conection.getContentLength();
                        // input stream to read file - with 8k buffer
                        input = new BufferedInputStream(url.openStream(), 8192);
                        //input = new BufferedInputStream(url.openStream(), 20000);
                        System.out.println("Data::" + passed.get(i).getFileName());
                        System.out.println("Data::" + filename);
                        // Output stream to write file
                        output = new FileOutputStream(getApplicationContext().getFilesDir() + "/" + filename);

                        byte data[] = new byte[1024];

                        long total = 0;

                        while ((count = input.read(data)) != -1) {
                            total += count;
                            // publishing the progress....
                            // After this onProgressUpdate will be called
                            publishProgress((int) ((total * 100) / lenghtOfFile));

                            // writing data to file
                            output.write(data, 0, count);
                        }
                        countfile+=1;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                pDialog.setMessage(countfile+" / "+ConstantClass.filecount);
                            }
                        });
                    }


                }
            } catch (Throwable t) {
                Log.e("AsyncTask", "OMGCrash", t);
                // maybe throw it again
                Toast.makeText(DownloadLoading.this,"There is a problem",Toast.LENGTH_SHORT).show();
                throw new RuntimeException(t);
            } finally {
                if (output != null) {
                    try {
                        output.flush();
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    /**
     * Updating progress bar
     */
    protected void onProgressUpdate(Integer... progress) {
        // setting progress percentage
       pDialog.setProgress(progress[0]);
    }

    /**
     * After completing background task Dismiss the progress dialog
     **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        //dismissDialog(progress_bar_type);

        if (error !=null){
            Toast.makeText(DownloadLoading.this, error.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }else if(!running){
            Log.d("Faild","Download fail connection");

        }else{
            Toast.makeText(DownloadLoading.this, "Success", Toast.LENGTH_SHORT).show();
        }
    }
}

} }

1 个答案:

答案 0 :(得分:0)

我想最佳解决方案是将服务 BroadCast

一起使用

这意味着你所有的下载服务

让我们说

public class DowloadService extends Service {

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
     Bundle extras = intent.getExtras();
       your_data = extras.get() // just example
 for (int i = 0; i < passed.size(); i++) {

                        File file = getBaseContext().getFileStreamPath(passed.get(i).getActualFilename());
                          if (file.exists()){
                                countfile+=1;
                               pDialog.setMessage(" Exist / "+ConstantClass.filecount);
                          }else{
                        Log.d("checkFilecount" + i, "fileName: " + passed.get(i).getFileName());
                        String filename = passed.get(i).getFileName().substring(passed.get(i).getFileName().lastIndexOf("/") + 1);
                        Log.d("checkFile", "name: " + filename);
                        URL url = new URL(passed.get(i).getFileName());
                        System.out.println("Data::" + passed.get(i).getFileName());
                        URLConnection conection = url.openConnection();
                        conection.connect();
                        // getting file length
                        int lenghtOfFile = conection.getContentLength();
                        // input stream to read file - with 8k buffer
                        input = new BufferedInputStream(url.openStream(), 8192);
                        //input = new BufferedInputStream(url.openStream(), 20000);
                        System.out.println("Data::" + passed.get(i).getFileName());
                        System.out.println("Data::" + filename);
                        // Output stream to write file
                        output = new FileOutputStream(getApplicationContext().getFilesDir() + "/" + filename);

                        byte data[] = new byte[1024];

                        long total = 0;

                        while ((count = input.read(data)) != -1) {
                            total += count;
                            // publishing the progress....
                            // After this onProgressUpdate will be called
                            publishProgress((int) ((total * 100) / lenghtOfFile));

                            // writing data to file
                            output.write(data, 0, count);
                        }
                        countfile+=1;

               //  send broadcast with data you want
ntent.putExtra("dataType",dataType);
                intent.putExtra("getAccuracy",gpsSignal);
           LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);

                            }
                        });
        return START_NOT_STICKY;
    }

}

然后在您的activiy Setup Local BroadCast中获取数据发送

 private class BroadCastLocal extends BroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent) {

            if (Constrains.PEDOMETERBROADCAST.equalsIgnoreCase(intent.getAction()))
            {
                int dataType = intent.getIntExtra("dataType",-1);


            }
        }

现在,只要用户开始/结束您的活动,该过程就不会生效