如何从doInBackground Asynctask android

时间:2019-03-20 06:50:37

标签: android-asynctask

我在AsyncTask中需要帮助。我正在使用async从url下载多个图像,它会一次下载所有图像。我面临的问题是用户面临互联网连接问题并且未下载图像时:doInBackground中有for循环来获取URL,并将其下载并保存到SD卡,如果下载成功,我将在本地DB中将标志位更新为1,如果不是,则应该为0。问题是doInBackground从循环返回最后一个值,或者如果使用arraylist来存储标志,则它将整个arraylist更新为1。但是我只希望将下载的图像ID发送给onPost Execute()方法并且只有该ID应该更新为1。我知道线程完成其任务后,它会将结果发送到onPostExecute(),但我没有得到它,在检查其状态时仍显示运行。我该如何解决。

我想要是否未下载图像,我想将标志位设置为其默认值0,如果将其位下载为1。

import java.util.ArrayList;
import java.util.List;

import android.view.View;

import android.widget.Button;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import static android.view.View.INVISIBLE;

public class Download_Activity extends AppCompatActivity {


    private static final int EXTERNAL_STORAGE_PERMISSION_CONSTANT = 100;
    private List<Model_Download> recList;
    String file_url;
    String folder_main = "Xs_Images";
    File file; // = your file
    String mimetype; // = your file's mimetype. MimeTypeMap may be useful.
    Button download_Btn;
    myDbAdapter helper;
    int id1,id;
    View v;
    int downloadStatus=1;
    int status=0;
    public static final int READ_TIMEOUT = 15000;
    public static final int CONNECTION_TIMEOUT = 15000;
    //int[] arr=new int[recList.size()];
    ArrayList<Integer> ids=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_);
        recList = new ArrayList<Model_Download>();
        recList = (ArrayList) getIntent().getParcelableArrayListExtra("downloads");
        download_Btn=(Button)findViewById(R.id.download);
        helper = new myDbAdapter(this);


        if (ActivityCompat.checkSelfPermission(Download_Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(Download_Activity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
        }
    }

    public void downloadImageFromUrl(View view){
        if (ActivityCompat.checkSelfPermission(Download_Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this,"No Permission",Toast.LENGTH_SHORT).show();
        } else {
            //  new MyAsyncTask().execute();
            new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, file_url);
            // Log.d("async","status "+asyncStatus);
               /* try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/
            // MyAsyncTask asyncTask = new MyAsyncTask();
            // asyncTask.execute();
            // downloadImageFromUrl();

            // MyAsyncTask asyncTask = new MyAsyncTask();
            // asyncTask.execute();
        }
    }

    class MyAsyncTask extends AsyncTask<String, String, ArrayList<Integer>> {
        private ProgressDialog progressDialog;
        @Override
        protected void onPreExecute() {

            super.onPreExecute();
            this.progressDialog = new ProgressDialog(Download_Activity.this);
            this.progressDialog.setMessage("Downloading file…");
            this.progressDialog.setIndeterminate(false);
            this.progressDialog.setMax(100);
            this.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            this.progressDialog.setCancelable(false);
            this.progressDialog.show();
        }

        @Override
        protected ArrayList<Integer> doInBackground(String... parms) {
            // download_Btn.setVisibility(INVISIBLE);
            for(Model_Download mddd:recList) {

                Status status=(getStatus());
                Log.d("status2","ids "+status);
                String url_select = mddd.getPic_id();
                id=mddd.getImages_id();


            /*    Log.d("id","pic id 1: "+id);
                for(int i=0;i<recList.size();i++)
                {
                    arr[i]=id=mddd.getImages_id();
                    Log.d("array","ids "+arr[i]);
                }*/

                try {
                    URL url = new URL(url_select);
                    //create the new connection
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    //set up some things on the connection
                    urlConnection.setRequestMethod("GET");
                    urlConnection.setDoOutput(true);
                    //urlConnection.setRequestMethod(REQUEST_METHOD);
                    urlConnection.setReadTimeout(READ_TIMEOUT);
                    urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
                    //and connect!
                    urlConnection.connect();
                    //set the path where we want to save the file in this case, going to save it on the root directory of the sd card.
                    // File SDCardRoot = Environment.getExternalStorageDirectory();


                    File f = new File(Environment.getExternalStorageDirectory(), folder_main);
                    if (!f.exists()) {
                        f.mkdirs();
                    }

             /*   File folder = getFilesDir();
                File f1= new File(folder, "doc_download");
                f.mkdir();*/

                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH);
                    String timeStamp = dateFormat.format(new Date());
                    String filename = "image-" + timeStamp + ".jpg";

                    //create a new file, specifying the path, and the filename which we want to save the file as.
                    file = new File(f, filename);
                    //this will be used to write the downloaded data into the file we created
                    FileOutputStream fileOutput = new FileOutputStream(file);
                    //this will be used in reading the data from the internet
                    InputStream inputStream = urlConnection.getInputStream();
                    //this is the total size of the file
                    int totalSize = urlConnection.getContentLength();
                    int lengthOfFile = urlConnection.getContentLength();
                    //variable to store total downloaded bytes
                    long downloadedSize = 0;
                    byte[] buffer = new byte[1024];
                    int bufferLength = 0; //used to store a temporary size of the buffer
                    //now, read through the input buffer and write the contents to the file
                    while ((bufferLength = inputStream.read(buffer)) > 0) {
                        //add the data in the buffer to the file in the file output stream (the file on the sd card
                        fileOutput.write(buffer, 0, bufferLength);
                        //add up the size so we know how much is downloaded
                        downloadedSize += bufferLength;
                        publishProgress("" + (int) ((downloadedSize * 100) / lengthOfFile));
                        Log.d("url", "Progress: " + (int) ((downloadedSize * 100) / lengthOfFile));
                        //this is where you would do something to report the prgress, like this maybe
                        // updateProgress(downloadedSize, totalSize);
                      /*  MediaScannerConnection.scanFile(Download_Activity.this,
                                new String[] { file.toString() }, null,
                                new MediaScannerConnection.OnScanCompletedListener() {
                                    public void onScanCompleted(String folder_main, Uri uri) {
                                        Log.i("ExternalStorage", "Scanned " + folder_main + ":");
                                        Log.i("ExternalStorage", "-> uri=" + uri);
                                    }
                                });*/

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Log.d("id","single id: "+id);
                Status status1=getStatus();
                Log.d("status","ids "+status);
                helper.updateStatus(id);
                ids.add(id);
              //  viewdata1(v);
                //return String.valueOf(id);
            }
            return null;
        }

        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            progressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(ArrayList<Integer> id) {
            // id=mddd.getImages_id();
            Log.d("id","pic id is: "+id);
            super.onPostExecute(id);

            this.progressDialog.dismiss();

           /* if(getStatus() == AsyncTask.Status.FINISHED) {


            }*/
           /* for(int i : id) {

                Log.d("ArrayList","pic id is: "+i);
                update(i);
            }*/
            Toast.makeText(getApplicationContext(),"Image Downloaded to sd card XXX Folder",Toast.LENGTH_LONG).show();
            // MediaScannerConnection.scanFile(Download_Activity.this, new String[]{file.getPath()}, null, null);
            // next_Btn.setVisibility(View.VISIBLE);
            MediaScannerConnection.scanFile(Download_Activity.this, new String[]{file.getPath()}, null, null);
            /*next_Btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MediaScannerConnection.scanFile(Download_Activity.this, new String[]{file.getPath()}, null, null);

                }
            });*/
           /* cancel(true);
            onCancelled();*/
            Status status1=getStatus();
            Log.d("cancel","ids "+status1);
            viewdata(v);


        }


    }
    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface arg0, int arg1) {
                        Log.d("DB", "before ");
                        viewdata1(v);
                        //helper.getImagesFromDB(String.valueOf(status));
                        Log.d("DB", "after ");
                        finish();
                    }
                }).create().show();
    }

    public void update(int image_id)
    {
     /*   for (Model_Download md : recList) {
            int ids = md.getImages_id();
            id1 = md.getImages_id();
            Log.d("urls", "wallet " + ids);*/

        helper.updateStatus(image_id);
        Messages.message(getApplicationContext(), "Updated");


    }
    public void viewdata(View view)
    {
        String data = helper.getData();
       /* Log.d("data","updated status is : ");
        Log.d("data","urls stored "+data);*/
        Messages.message(this,data);
    }
    public void viewdata1(View view)
    {

        List<Model_Photos> data = helper.getURLS();
        for(Model_Photos d : data) {
            int id= d.getImages_id();
            String url=d.getModelViewPhotoURL();
            // Log.d("data","updated status is : ");
           /* Log.d("database1", "data " + d);
            Log.d("database1", "id is " + id);
            Log.d("database1", "urls is " + url);*/
            //Messages.message(this, d);
        }

    }



}

0 个答案:

没有答案