0

I want to check whether a thread is completed or not.I want to download some data, when the download is completed then want to toast a message download completed .Here is my code and I used btn on click method to start the download.Now I want to check whether the download is completed.

public void startDownload(final int position) {

        Runnable runnable = new Runnable() {
            int Status = 0;

            public void run() {
                Log.v("thread", "thread rtun ");
                String urlDownload = MyArrList.get(position)
                        .get("VideoPathThum").toString();
                Log.v("log_tag", "urlDownload   ::: " + urlDownload
                        + "Position StartDownload ::: " + position);

                int count = 0;
                try {

                    URL url = new URL(urlDownload);
                    URLConnection conexion = url.openConnection();
                    conexion.connect();

                    int lenghtOfFile = conexion.getContentLength();
                    // Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

                    InputStream input = new BufferedInputStream(
                            url.openStream());

                    // Get File Name from URL
                    String fileName = urlDownload.substring(
                            urlDownload.lastIndexOf('/') + 1,
                            urlDownload.length());
                    download = new File(
                            Environment.getExternalStorageDirectory()
                                    + "/download/");
                    if (!download.exists()) {
                        download.mkdir();
                    }
                    strDownloaDuRL = download + "/" + fileName;
                    OutputStream output = new FileOutputStream(strDownloaDuRL);

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

                    while ((count = input.read(data)) != -1) {

                        if (Thread.interrupted() == true) {
                            Log.v("log_tag", " interrupt");
                            output.flush();
                            output.close();
                            input.close();
                            updateStatus(position, 0);
                            SetMainProgressbar();
                            break;
                        }

                        total += count;
                        Status = (int) ((total * 100) / lenghtOfFile);
                        output.write(data, 0, count);

                        TestScrollNewDownloadActivity.this
                                .runOnUiThread(new Runnable() {
                                    public void run() {
                                        updateStatus(position, Status);
                                        SetMainProgressbar();
                                        // BusyExtMemory();

                                    }
                                });
                    }
                    output.flush();
                    output.close();
                    input.close();

                } catch (Exception e) {
                }

            }
        };

        tr = new Thread(runnable);
        tr.start();
        trlist.set(position, tr);

    }
4

3 回答 3

2

为此使用 AysncTask()。它比线程更好

DownloadAsync download = new DownloadAsync(position);
download.execute();


private class DownloadAsync extends AsyncTask<Void, Void, Void> {

    int pos;

    public incidentDetailAsync(int position) {

        pos = position;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        try {
            progressDilaog = ProgressDialog.show(ActivityA.this,
                    "", "Loading", true, false);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected Void doInBackground(Void... params) {

        try {
              String urlDownload = MyArrList.get(position)
                    .get("VideoPathThum").toString();
            Log.v("log_tag", "urlDownload   ::: " + urlDownload
                    + "Position StartDownload ::: " + position);

            int count = 0;
            try {

                URL url = new URL(urlDownload);
                URLConnection conexion = url.openConnection();
                conexion.connect();

                int lenghtOfFile = conexion.getContentLength();
                // Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

                InputStream input = new BufferedInputStream(
                        url.openStream());

                // Get File Name from URL
                String fileName = urlDownload.substring(
                        urlDownload.lastIndexOf('/') + 1,
                        urlDownload.length());
                download = new File(
                        Environment.getExternalStorageDirectory()
                                + "/download/");
                if (!download.exists()) {
                    download.mkdir();
                }
                strDownloaDuRL = download + "/" + fileName;
                OutputStream output = new FileOutputStream(strDownloaDuRL);

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

                while ((count = input.read(data)) != -1) {

                    if (Thread.interrupted() == true) {
                        Log.v("log_tag", " interrupt");
                        output.flush();
                        output.close();
                        input.close();
                        updateStatus(position, 0);
                        SetMainProgressbar();
                        break;
                    }

                    total += count;
                    Status = (int) ((total * 100) / lenghtOfFile);
                    output.write(data, 0, count);

                    TestScrollNewDownloadActivity.this
                            .runOnUiThread(new Runnable() {
                                public void run() {
                                    updateStatus(position, Status);
                                    SetMainProgressbar();
                                    // BusyExtMemory();

                                }
                            });
                }
                output.flush();
                output.close();
                input.close();

            } catch (Exception e) {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        progressDilaog.dismiss();

        Toast.makeText(ActivityA.this,
                "Successfully Download", Toast.LENGTH_LONG).show();


    }
}
于 2013-03-22T06:54:43.853 回答
0

使用AysncTask()

调用使用: new AsyncAction().execute(null,null,null);

private class AsyncAction extends AsyncTask<String, Void, String> 
    {
         public boolean status=false;
        private ProgressDialog pd;
        @Override
        protected String doInBackground(String... arg0) 
        {
            // TODO Auto-generated method stub
            try
              {

            // download code

 String urlDownload = MyArrList.get(position)
                        .get("VideoPathThum").toString();
                Log.v("log_tag", "urlDownload   ::: " + urlDownload
                        + "Position StartDownload ::: " + position);

                int count = 0;
                try {

                    URL url = new URL(urlDownload);
                    URLConnection conexion = url.openConnection();
                    conexion.connect();

                    int lenghtOfFile = conexion.getContentLength();
                    // Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

                    InputStream input = new BufferedInputStream(
                            url.openStream());

                    // Get File Name from URL
                    String fileName = urlDownload.substring(
                            urlDownload.lastIndexOf('/') + 1,
                            urlDownload.length());
                    download = new File(
                            Environment.getExternalStorageDirectory()
                                    + "/download/");
                    if (!download.exists()) {
                        download.mkdir();
                    }
                    strDownloaDuRL = download + "/" + fileName;
                    OutputStream output = new FileOutputStream(strDownloaDuRL);

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

                    while ((count = input.read(data)) != -1) {

                        if (Thread.interrupted() == true) {
                            Log.v("log_tag", " interrupt");
                            output.flush();
                            output.close();
                            input.close();
                            updateStatus(position, 0);
                            SetMainProgressbar();
                            break;
                        }

                        total += count;
                        Status = (int) ((total * 100) / lenghtOfFile);
                        output.write(data, 0, count);

                        TestScrollNewDownloadActivity.this
                                .runOnUiThread(new Runnable() {
                                    public void run() {
                                        updateStatus(position, Status);
                                        SetMainProgressbar();
                                        // BusyExtMemory();

                                    }
                                });
                    }
                    output.flush();
                    output.close();
                    input.close();

                } catch (Exception e) {
                }

            }


                  status=true;

            } 
              catch (Exception e) 
              {
                // TODO: handle exception
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) 
        {

           pd.dismiss();
    Toast.makeText(ActivityA.this,
                "Successfully Download", Toast.LENGTH_LONG).show();


        }

        protected void onPreExecute() 
        {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pd = new ProgressDialog(ticket_detail.this);
            pd.setMessage("Please Wait ...");
            pd.setIndeterminate(true);
            pd.setCancelable(false);
            pd.show();
        }

    }
于 2013-03-22T06:56:57.657 回答
0

最简单的方法是使用http://developer.android.com/reference/android/os/AsyncTask.html。将要运行的代码放在 doInBackground 中的单独线程上。在 onPostExecute 中单独线程完成后,将要运行的代码放在 UI 线程上。

于 2013-03-22T06:55:17.607 回答