DownloadManager
Androidには、この目的のためだけに呼び出されるAPIが含まれていました...しかし、2.3でリリースされました。そのため、2.2を対象とするアプリケーションでは役に立ちませんが、実装を調査するための優れたリソースになる可能性があります。
私がお勧めする簡単な実装は次のようなものです。
- を使用し
HttpURLConnection
て接続し、データをダウンロードします。これには、マニフェストでインターネット権限を宣言する必要があります
- ファイルを配置する場所を決定します。デバイスのSDカードに保存する場合は、WRITE_EXTERNAL_STORAGE権限も必要です。
- この操作を。のdoInBackground()メソッドでラップし
AsyncTask
ます。これは長時間実行される操作であるため、AsyncTaskが管理するバックグラウンドスレッドに配置する必要があります。
- これを実装して
Service
、ユーザーがアクティビティをフォアグラウンドに保持しなくても操作を保護して実行できるようにします。
NotificationManager
ダウンロードが完了したときにユーザーに通知するために使用します。これにより、ステータスバーにメッセージが投稿されます。
さらに単純化するために、を使用するIntentService
と、スレッドが処理され(すべてonHandleIntent
がバックグラウンドスレッドで呼び出されます)、複数のインテントを送信するだけで、一度に1つずつ処理するために複数のダウンロードをキューに入れることができます。これが私が言っていることのスケルトンの例です:
public class DownloadService extends IntentService {
public static final String EXTRA_URL = "extra_url";
public static final int NOTE_ID = 100;
public DownloadService() {
super("DownloadService");
}
@Override
protected void onHandleIntent(Intent intent) {
if(!intent.hasExtra(EXTRA_URL)) {
//This Intent doesn't have anything for us
return;
}
String url = intent.getStringExtra(EXTRA_URL);
boolean result = false;
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//Input stream from the connection
InputStream in = new BufferedInputStream(connection.getInputStream());
//Output stream to a file in your application's private space
FileOutputStream out = openFileOutput("filename", Activity.MODE_PRIVATE);
//Read and write the stream data here
result = true;
} catch (Exception e) {
e.printStackTrace();
}
//Post a notification once complete
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification note;
if(result) {
note = new Notification(0, "Download Complete", System.currentTimeMillis());
} else {
note = new Notification(0, "Download Failed", System.currentTimeMillis());
}
manager.notify(NOTE_ID, note);
}
}
次に、次のようなアクティビティの任意の場所にダウンロードするURLを使用してこのサービスを呼び出すことができます。
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra(DownloadService.EXTRA_URL,"http://your.url.here");
startService(intent);
お役に立てば幸いです。
編集:私はこの例を修正して、後でこれに遭遇した人のために不要なダブルスレッドを削除します。