0

スレッドが完了したかどうかを確認したい。いくつかのデータをダウンロードしたい。ダウンロードが完了したら、メッセージのダウンロードが完了したことをトーストしたい。これが私のコードであり、クリックメソッドでbtnを使用してダウンロードを開始した。ダウンロードが完了したか確認したい。

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

最も簡単な方法は、http://developer.android.com/reference/android/os/AsyncTask.htmlを使用することです。実行するコードをdoInBackgroundの別のスレッドに配置します。別のスレッドがonPostExecuteで終了した後、実行するコードをUIスレッドに配置します。

于 2013-03-22T06:55:17.607 に答える
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 に答える