チラシの裏

DownloadManagerをつかってみた2

2012.03.04

前回の記事の追加でダウンロード完了時の処理をやってみた 以下ソース

DownloadManager mManager;
long mDownloadId;

//
// onCreateは省略
//

private void download() {
    String url = "http://developer.android.com/assets/images/home/ics-android.png"
    
    String sdcardPath = Environment.getExternalStorageDirectory().getPath();
    String dirName = "DownloadTest";

    File file = new File(sdcardPath, dirName);
    if(!file.exists())file.mkdirs();
    
    Request r = new Request(Uri.parse(url));
    r.setDestinationInExternalPublicDir(dirName, System.currentTimeMillis() + ".png");
    r.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
    mDownloadId = mManager.enqueue(r);
    Log.d(TAG, "ID = " + mDownloadId);
}

private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive");
        Query query = new Query();
        query.setFilterById(mDownloadId);
        Log.d(TAG, "ID = " + mDownloadId);
        Cursor c = mManager.query(query);
        if(c.moveToFirst()) {
            int colReason = c.getColumnIndex(DownloadManager.COLUMN_REASON);
            int reason = c.getInt(colReason);
            Log.d(TAG, ""+reason);
            int colStatus = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
            int status = c.getInt(colStatus);
            Log.d(TAG, "" + status);
        }
    }
};

@Override
protected void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    registerReceiver(receiver, filter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
}

変数reasonやstatusの詳細はhttp://developer.android.com/reference/android/app/DownloadManager.htmlを参照

comments powered by Disqus