URLからAndroid 2.2でデータファイル5-40 MBをダウンロードします。開発に使用するクラスはどれですか?

StackOverflow https://stackoverflow.com/questions/4866679

質問

ファイル(.zip / .txt / .jpgなど)サイズ5〜50 MBをダウンロードする必要があるアプリケーションを開発しています。Android2.2に基づくアプリケーション。

ユーザーが提供します URL ダウンロードをトリガーしますが、ダウンロードプロセスは完了するまでバックグラウンドで実行されます。

ストリーミング ファイルのダウンロードに使用する必要があります。
これをどのように使用できるか知りたい HTTP接続.
クラス これに使用できますか?
Android 2.2はこれにAPIを提供しますか?

どんな種類の助けも感謝しています。

役に立ちましたか?

解決

Androidには、呼ばれるAPIが含まれていました DownloadManager まさにこの目的のために...しかし、それは2.3でリリースされました。したがって、2.2をターゲットにするアプリケーションでは役に立つことはありませんが、実装を調査するための良いリソースかもしれません。

私がお勧めする簡単な実装は次のようなものです:

  • ANを使用してください HttpURLConnection データを接続してダウンロードします。これには、インターネットの許可があなたのマニフェストで宣言される必要があります
  • ファイルがどこにあるかを決定します。デバイスのSDカードでそれを必要とする場合は、write_external_storageの許可も必要です。
  • この操作をdoinbackground()メソッドに包みます AsyncTask. 。これは長期にわたる操作であるため、Asynctaskが管理するバックグラウンドスレッドに入れる必要があります。
  • これをaに実装します Service そのため、ユーザーがANアクティビティを前景に保持せずに操作を実行できます。
  • 使用する NotificationManager ダウンロードが完了したときにユーザーに通知するには、ステータスバーにメッセージを投稿します。

使用する場合、物事をさらに単純化するため IntentService, 、それはあなたのためのスレッドを処理します(すべての onHandleIntent バックグラウンドスレッドで呼び出されます)、複数のダウンロードを1つずつ処理して、複数の意図を送信するだけで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);

それが役立つことを願っています!

編集: この例を修正して、後でこれに出くわす人のために不必要な二重スレッドを削除します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top