Androidでファイルをダウンロードし、ProgressDialogで進行状況を表示する 質問する

Androidでファイルをダウンロードし、ProgressDialogで進行状況を表示する 質問する

更新される簡単なアプリケーションを作成しようとしています。そのためには、ファイルをダウンロードして、現在の進行状況を表示できる簡単な関数が必要です。のProgressDialog実行方法はわかっていますProgressDialogが、現在の進行状況を表示する方法と、そもそもファイルをダウンロードする方法がよくわかりません。

ベストアンサー1

ファイルをダウンロードする方法はたくさんあります。以下に最も一般的な方法を記載します。どの方法がアプリに適しているかは、あなた次第です。

1.AsyncTaskダウンロードの進行状況をダイアログで表示する

この方法を使用すると、いくつかのバックグラウンド プロセスを実行し、同時に UI を更新できます (この場合は、進行状況バーを更新します)。

輸入品:

import android.os.PowerManager;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;

これはサンプルコードです:

// declare the dialog as a member field of your activity
ProgressDialog mProgressDialog;

// instantiate it within the onCreate method
mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);

// execute this when the downloader must be fired
final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");

mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

    @Override
    public void onCancel(DialogInterface dialog) {
        downloadTask.cancel(true); //cancel the task
    }
});

次のようになりますAsyncTask:

// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {

    private Context context;
    private PowerManager.WakeLock mWakeLock;

    public DownloadTask(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(String... sUrl) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }

            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();
            output = new FileOutputStream("/sdcard/file_name.extension");

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled()) {
                    input.close();
                    return null;
                }
                total += count;
                // publishing the progress....
                if (fileLength > 0) // only if total length is known
                    publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }

上記のメソッド ( doInBackground) は常にバックグラウンド スレッドで実行されます。そこで UI タスクを実行しないでください。一方、 と はonProgressUpdateUIonPreExecuteスレッドで実行されるため、そこで進行状況バーを変更できます。

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // take CPU lock to prevent CPU from going off if the user 
        // presses the power button during download
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
             getClass().getName());
        mWakeLock.acquire();
        mProgressDialog.show();
    }
    
    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        // if we get here, length is known, now set indeterminate to false
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgress(progress[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        mWakeLock.release();
        mProgressDialog.dismiss();
        if (result != null)
            Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
        else
            Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
    }
}

これを実行するには、WAKE_LOCK 権限が必要です。

<uses-permission android:name="android.permission.WAKE_LOCK" />

2. サービスからダウンロード

ここでの大きな疑問は、サービスからアクティビティを更新するにはどうすればよいかということです。次の例では、おそらくご存じない 2 つのクラス、ResultReceiverおよびを使用しますIntentService。はResultReceiver、サービスからスレッドを更新できるようにするクラスです。は、そこからバックグラウンド作業を行うスレッドを生成するIntentServiceのサブクラスです(は実際にはアプリの同じスレッドで実行されることに注意してください。 を拡張する場合は、CPU ブロッキング操作を実行するために手動で新しいスレッドを生成する必要があります)。ServiceServiceService

ダウンロード サービスは次のようになります。

public class DownloadService extends IntentService {
    public static final int UPDATE_PROGRESS = 8344;

    public DownloadService() {
        super("DownloadService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {

        String urlToDownload = intent.getStringExtra("url");
        ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
        try {
            
            //create url and connect
            URL url = new URL(urlToDownload);
            URLConnection connection = url.openConnection();
            connection.connect();

            // this will be useful so that you can show a typical 0-100% progress bar
            int fileLength = connection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(connection.getInputStream());

            String path = "/sdcard/BarcodeScanner-debug.apk" ;
            OutputStream output = new FileOutputStream(path);

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;

                // publishing the progress....
                Bundle resultData = new Bundle();
                resultData.putInt("progress" ,(int) (total * 100 / fileLength));
                receiver.send(UPDATE_PROGRESS, resultData);
                output.write(data, 0, count);
            }

            // close streams 
            output.flush();
            output.close();
            input.close();

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

        Bundle resultData = new Bundle();
        resultData.putInt("progress" ,100);

        receiver.send(UPDATE_PROGRESS, resultData);
    }
}

マニフェストにサービスを追加します。

<service android:name=".DownloadService"/>

アクティビティは次のようになります。

// initialize the progress dialog like in the first example

// this is how you fire the downloader
mProgressDialog.show();
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra("url", "url of the file to download");
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);

ここで、ResultReceiver遊びに来てください:

private class DownloadReceiver extends ResultReceiver{

    public DownloadReceiver(Handler handler) {
        super(handler);
    }

    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {

        super.onReceiveResult(resultCode, resultData);

        if (resultCode == DownloadService.UPDATE_PROGRESS) {

            int progress = resultData.getInt("progress"); //get the progress
            dialog.setProgress(progress);

            if (progress == 100) {
                dialog.dismiss();
            }
        }
    }
}

2.1 Groundyライブラリを使用する

グラウディResultReceiverは、基本的にバックグラウンド サービスでコードを実行するのに役立つライブラリであり、上記の概念に基づいています。このライブラリは現在非推奨です。コード全体は次のようになります。

ダイアログを表示するアクティビティ...

public class MainActivity extends Activity {

    private ProgressDialog mProgressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        findViewById(R.id.btn_download).setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String url = ((EditText) findViewById(R.id.edit_url)).getText().toString().trim();
                Bundle extras = new Bundler().add(DownloadTask.PARAM_URL, url).build();
                Groundy.create(DownloadExample.this, DownloadTask.class)
                        .receiver(mReceiver)
                        .params(extras)
                        .queue();

                mProgressDialog = new ProgressDialog(MainActivity.this);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(false);
                mProgressDialog.show();
            }
        });
    }

    private ResultReceiver mReceiver = new ResultReceiver(new Handler()) {
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            super.onReceiveResult(resultCode, resultData);
            switch (resultCode) {
                case Groundy.STATUS_PROGRESS:
                    mProgressDialog.setProgress(resultData.getInt(Groundy.KEY_PROGRESS));
                    break;
                case Groundy.STATUS_FINISHED:
                    Toast.makeText(DownloadExample.this, R.string.file_downloaded, Toast.LENGTH_LONG);
                    mProgressDialog.dismiss();
                    break;
                case Groundy.STATUS_ERROR:
                    Toast.makeText(DownloadExample.this, resultData.getString(Groundy.KEY_ERROR), Toast.LENGTH_LONG).show();
                    mProgressDialog.dismiss();
                    break;
            }
        }
    };
}

Groundyがファイルをダウンロードして進行状況を表示するためにGroundyTask使用する実装:

public class DownloadTask extends GroundyTask {    
    public static final String PARAM_URL = "com.groundy.sample.param.url";

    @Override
    protected boolean doInBackground() {
        try {
            String url = getParameters().getString(PARAM_URL);
            File dest = new File(getContext().getFilesDir(), new File(url).getName());
            DownloadUtils.downloadFile(getContext(), url, dest, DownloadUtils.getDownloadListenerForTask(this));
            return true;
        } catch (Exception pokemon) {
            return false;
        }
    }
}

これをマニフェストに追加するだけです:

<service android:name="com.codeslap.groundy.GroundyService"/>

こんなに簡単なことはないと思います。最新の瓶を手に入れるだけですGithubからこれで準備完了です。Groundy の主な目的は、バックグラウンド サービスで外部 REST API を呼び出し、その結果を簡単に UI に投稿することだということを覚えておいてくださいアプリでそのようなことを行っている場合、Groundy は非常に便利です。

2.2 使用https://github.com/koush/ion

3.DownloadManagerクラスを使用する(GingerBread以降のバージョンのみ)

DownloadManagerGingerBreadには、ファイルを簡単にダウンロードし、スレッドやストリームなどの処理の面倒な作業をシステムに委任できる新しい機能が導入されました。

まず、ユーティリティ メソッドを見てみましょう。

/**
 * @param context used to check the device version and DownloadManager information
 * @return true if the download manager is available
 */
public static boolean isDownloadManagerAvailable(Context context) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        return true;
    }
    return false;
}

メソッドの名前がす​​べてを説明しています。 がDownloadManager利用可能であることが確認できたら、次のように実行できます。

String url = "url you want to download";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Some descrition");
request.setTitle("Some title");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name-of-the-file.ext");

// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);

ダウンロードの進行状況は通知バーに表示されます。

最終的な考え

1 番目と 2 番目の方法はほんの一角にすぎません。アプリを堅牢なものにするには、考慮すべき点が数多くあります。以下に簡単なリストを示します。

  • ユーザーがインターネットに接続できるかどうかを確認する必要があります
  • インターネットの可用性を確認する場合も、適切な権限 (INTERNETおよびWRITE_EXTERNAL_STORAGE)があることを確認してください。ACCESS_NETWORK_STATE
  • ファイルをダウンロードするディレクトリが存在し、書き込み権限があることを確認してください。
  • ダウンロードが大きすぎる場合は、以前の試行が失敗した場合にダウンロードを再開する方法を実装することをお勧めします。
  • ダウンロードを中断できるようにしていただければ、ユーザーは感謝するでしょう。

ダウンロードプロセスの詳細な制御が必要でない限り、DownloadManager(3) の使用を検討してください。これは、上記の項目のほとんどをすでに処理しているためです。

しかし、ニーズが変化する可能性も考慮してください。例えば、DownloadManager 応答キャッシュは行いません. 同じ大きなファイルを何度もダウンロードしてしまいます。事後的にこれを修正する簡単な方法はありません。基本的なHttpURLConnection(1, 2) から始める場合、必要なのは を追加することだけですHttpResponseCache。したがって、基本的な標準ツールを学習するための最初の努力は、良い投資になる可能性があります。

このクラスは API レベル 26 で非推奨になりました。ProgressDialog はモーダル ダイアログであり、ユーザーがアプリを操作できないようにします。このクラスを使用する代わりに、アプリの UI に埋め込むことができる ProgressBar などの進行状況インジケーターを使用する必要があります。または、通知を使用してタスクの進行状況をユーザーに通知することもできます。詳細については、リンク

おすすめ記事