2010年12月19日日曜日

Android Android2.3 - DownloadManager を使う

DownloadManager は long-running HTTP ダウンロード用のシステムサービス

・ダウンロードするファイルのURIを指定してリクエストする

・ダウンロードはバックグラウンドで行われる

・接続が変わったり、リブートしたり、ダウンロードに失敗した場合は再試行される

・getSystemService(String) メソッドの引数に DOWNLOAD_SERVICE を渡してインスタンスを取得する

・このAPIを使ってダウンロードをリクエストするアプリは、ユーザーが notification や downloads UI からダウンロードを開始したことを適切にハンドルするために、ACTION_NOTIFICATION_CLICKED に対する broadcast receiver を登録しておかなければならない



# DownloadManager.Query に渡す URI が https だと怒られた。http じゃないとだめみたい。

# AndoridManifest.xml に <uses-permission android:name="android.permission.INTERNET"/> が必要なのですが、これを書かない時の logcat のエラーメッセージが requires android.permission.ACCESS_ALL_DOWNLOADS or android.permission.ACCESS_ALL_DOWNLOADS (エミュレータで、ですけど。)という(トンチンカン?な internal permission を表示してしまう)ものなので、ちょっと紛らわしいです。


保存先を明示しない場合は、cache にだけ保存されます。

$ adb -e shell
# ls cache
image1-3.png
image1-2.png
image1-1.png
image1.png
backup
lost+found



永続化する場合は、外部メディアのURIを指定します。


// save with uri
File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "image1.png");
mRequest.setDestinationUri(Uri.fromFile(file));


# setDestinationUri() の引数に内部メディアのURIを入れると怒られます。。。


保存先を外部メディアの Application's Directory にした場合は /mnt/sdcard/ とかの下の Android/data/package-name/files/ の下の setDestinationInExternalPublicDir() の第1引数で指定したディレクトリの中になります。


mRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, "image1.png");
File pathExternalDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
pathExternalDir.mkdirs();



$ adb -e shell
# ls mnt/sdcard/Android/data/yanzm.example.downloadmanagersample/files/Download
image1.png



保存先を外部メディアの Public Directory にした場合は /mnt/sdcard/ とかの下の setDestinationInExternalPublicDir() の第1引数で指定したディレクトリの中になります。


mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "image1.png");
File pathExternalPublicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
pathExternalPublicDir.mkdirs();



$ adb -e shell
# ls mnt/sdcard/Download
image1.png



# mkdirs() でディレクトリ作っておかないとダウンロードに失敗するので気をつけて。。。


全ソースはこちら

package yanzm.example.downloadmanagersample;

import java.io.File;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;

public class MyActivity extends Activity {

private int downloadDestination = DESTINATION_EXTERNAL_PUBLICDIR;

private static final int CACHE = 0;
private static final int DESTINATION_URI = 1;
private static final int DESTINATION_EXTERNAL_DIR = 2;
private static final int DESTINATION_EXTERNAL_PUBLICDIR = 3;

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

public void startDownload(View v) {
DownloadManager mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

Uri uri = Uri.parse("http://sites.google.com/site/yukianzm/tmp/image1.png");

DownloadManager.Request mRequest = new DownloadManager.Request(uri);
mRequest.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE);
// mRequest.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
// mRequest.setAllowedOverRoaming(false);
mRequest.setTitle("Test Download!");
mRequest.setDescription("sample of using download manager");

switch (downloadDestination) {
case CACHE:
break;
case DESTINATION_URI:
// save with uri
File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "image1.png");
mRequest.setDestinationUri(Uri.fromFile(file));
break;
case DESTINATION_EXTERNAL_DIR:
// save in external storage application's directory
mRequest.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DOWNLOADS, "image1.png");
File pathExternalDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
pathExternalDir.mkdirs();
break;
case DESTINATION_EXTERNAL_PUBLICDIR:
// save in external storage public directory
mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "image1.png");
File pathExternalPublicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
pathExternalPublicDir.mkdirs();
break;
}

// mRequest.setMimeType(HTTP.OCTET_STREAM_TYPE);
mRequest.setShowRunningNotification(true);
mRequest.setVisibleInDownloadsUi(true);

long downloadId = mDownloadManager.enqueue(mRequest);

Log.d("DownloadManagerSample", "Start Download download Id = " + downloadId);
}
}



# broadcast receiver 部分についてはまた今度。。。

2.3 の Built-in Application の Downloads でみてみるとこんな感じ。






■ Nested Classes
 - DownloadManager.Query
    ダウンロードマネジャークエリーをフィルターするのに使う

 - DwonloadManager.Request
    新しいダウンロードのリクエストに必要な全ての情報を含む


■Constants
 - ACTION_DOWNLOAD_COMPLETE
    ダウンロードが完了したときに download manager によって
    発行される broadcast intent action

 - ACTION_NOTIFICATION_CLICKED
    ユーザーが system notification や downloads UI から
    実行中のダウンロードをクリックしたときに download manager
    から発行される broadcast intent action

 - ACTION_VIEW_DOWNLOADS
    全ダウンロードを表示するための Activity を起動する intent action

 - COLUMN_BYTES_DOWNLOADED_SO_FAR
    これまでのダウンロードバイト数

 - COLUMN_DESCRIPTION
    クライアントが提供するこのダウンロードの詳細

 - COLUMN_ID
    特定のダウンロードの識別子。システム上でユニーク

 - COLUMN_LAST_MODIFIED_TIMESTAMP
    最後にダウンロードが編集されたタイムスタンプ
     (System.currentTimeMillis() UTC)

 - COLUMN_LOCAL_URI
    ダウンロードされたファイルが保存される場所のUri

 - COLUMN_MEDIAPROVIDER_URI
    このダウンロードエントリに対応する MediaProvider でのエントリへのURI

 - COLUMN_MEDIA_TYPE
    このダウンロードファイルの Internet Media Type

 - COLUMN_REASON
    ダウンロードのステータスの詳細を提供する
    ERROR_* か PAUSED_* の定数の1つ

    - ERROR_CANNNOT_RESUME
       一時的なエラーでダウンロードを再開できない

    - ERROR_DEVICE_NOT_FOUND
       外部ストレージデバイスがみつからない

    - ERROR_FILE_ALREADY_EXISTS
       リクエスト先のファイルがすでに存在している
       (download manager はすでに存在している
       ファイルを上書きしない)

    - ERROR_FILE_ERROR
       他のエラーコードに合致しないストレージ問題が起こった

    - ERROR_HTTP_DATA_ERROR
       データを受信もしくは解析中にHTTPレベルでエラーが起こった

    - ERROR_INSUFFICIENT_SPACE
       十分なストレージ領域がない

    - ERROR_TOO_MANY_REDIRECTS
       リダイレクトが多すぎる

    - ERROR_UNHANDLED_HTTP_CODE
       download manager がハンドルできない HTTP code を受信した

    - ERROR_UNKNOWN
       他のエラーコードに合致しないエラーでダウンロードが完了した

    - PAUSED_QUEUED_FOR_WIFI
       ダウンロードが mobile network を介すときのリミットサイズ
       を超えたので、download manager は Wi-Fi 接続による再開を
       待っている

    - PAUSED_UNKNOWN
       ダウンロードは何かの理由で一時停止している

    - PAUSED_WAITING_FOR_NETWORK
       ダウンロードは再開のためにネットワーク接続を待っている

    - PAUSED_WAITING_TO_RETRY
       ネットワークエラーが発生し、download manager はリクエストを
       再試行する前に待っているので、ダウンロードが一時停止している

 - COLUMN_STATUS
    ダウンロードの現在の状態。STATUS_* 定数の1つ

    - STATUS_FAILED
       ダウンロードが失敗したときの値
       (再試行はされない)

    - STATUS_PAUSED
       ダウンロードが再試行か再開を待っているときの値

    - STATUS_PENDING
       ダウンロードが開始されるのを待っているときの値

    - STATUS_RUNNING
       ダウンロードが実行されているときの値

    - STATUS_SUCCESSFUL
       ダウンロードが成功し完了したときの値


 - COLUMN_TITLE
    クライアントが提供するこのダウンロードのタイトル

 - COLUMN_TOTAL_SIZE_BYTES
    ダウンロードのトータルバイト数

 - COLUMN_URI
    ダンロードする URI

 - EXTRA_DOWNLOAD_ID
    ACTION_DOWNLOAD_COMPLETE intents に含まれる
    intent extra
    今完了したダウンロードのID (long値)

■ Public Methods

 - long enqueue(DownloadManager.Request request)
    新しいダウンロードをキューに入れる

 - ParcelFileDescriptor openDonwloadedFile(long id)
    ダウンロードしたファイルを読むために開く

 - Cursor query(DownloadManager.Query query)
    リクエストされているダウンロードについてのクエリ

 - int remove(long... ids)
    ダウンロードをキャンセルし、download manager から削除する

2 件のコメント:

'},ClipboardSwf:null,Version:'1.5.1'}};dp.SyntaxHighlighter=dp.sh;dp.sh.Toolbar.Commands={ExpandSource:{label:'+ expand source',check:function(highlighter){return highlighter.collapse;},func:function(sender,highlighter) {sender.parentNode.removeChild(sender);highlighter.div.className=highlighter.div.className.replace('collapsed','');}},ViewSource:{label:'view plain',func:function(sender,highlighter) {var code=dp.sh.Utils.FixForBlogger(highlighter.originalCode).replace(/'+code+'');wnd.document.close();}},CopyToClipboard:{label:'copy to clipboard',check:function(){return window.clipboardData!=null||dp.sh.ClipboardSwf!=null;},func:function(sender,highlighter) {var code=dp.sh.Utils.FixForBlogger(highlighter.originalCode).replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');if(window.clipboardData) {window.clipboardData.setData('text',code);} else if(dp.sh.ClipboardSwf!=null) {var flashcopier=highlighter.flashCopier;if(flashcopier==null) {flashcopier=document.createElement('div');highlighter.flashCopier=flashcopier;highlighter.div.appendChild(flashcopier);} flashcopier.innerHTML='';} alert('The code is in your clipboard now');}},PrintSource:{label:'print',func:function(sender,highlighter) {var iframe=document.createElement('IFRAME');var doc=null;iframe.style.cssText='position:absolute;width:0px;height:0px;left:-500px;top:-500px;';document.body.appendChild(iframe);doc=iframe.contentWindow.document;dp.sh.Utils.CopyStyles(doc,window.document);doc.write('

'+highlighter.div.innerHTML+'

');doc.close();iframe.contentWindow.focus();iframe.contentWindow.print();alert('Printing...');document.body.removeChild(iframe);}},About:{label:'?',func:function(highlighter) {var wnd=window.open('','_blank','dialog,width=300,height=150,scrollbars=0');var doc=wnd.document;dp.sh.Utils.CopyStyles(doc,window.document);doc.write(dp.sh.Strings.AboutDialog.replace('{V}',dp.sh.Version));doc.close();wnd.focus();}}};dp.sh.Toolbar.Create=function(highlighter) {var div=document.createElement('DIV');div.className='tools';for(var name in dp.sh.Toolbar.Commands) {var cmd=dp.sh.Toolbar.Commands[name];if(cmd.check!=null&&!cmd.check(highlighter)) continue;div.innerHTML+=''+cmd.label+'';} return div;} dp.sh.Toolbar.Command=function(name,sender) {var n=sender;while(n!=null&&n.className.indexOf('dp-highlighter')==-1) n=n.parentNode;if(n!=null) dp.sh.Toolbar.Commands[name].func(sender,n.highlighter);} dp.sh.Utils.CopyStyles=function(destDoc,sourceDoc) {var links=sourceDoc.getElementsByTagName('link');for(var i=0;i');} dp.sh.Utils.FixForBlogger=function(str) {return(dp.sh.isBloggerMode==true)?str.replace(/
|<br\s*\/?>/gi,''):str;} dp.sh.RegexLib={MultiLineCComments:new RegExp('/\\*[\\s\\S]*?\\*/','gm'),SingleLineCComments:new RegExp('//.*$','gm'),SingleLinePerlComments:new RegExp('#.*$','gm'),DoubleQuotedString:new RegExp('"(?:\\.|(\\\\\\")|[^\\""\\n])*"','g'),SingleQuotedString:new RegExp("'(?:\\.|(\\\\\\')|[^\\''\\n])*'",'g')};dp.sh.Match=function(value,index,css) {this.value=value;this.index=index;this.length=value.length;this.css=css;} dp.sh.Highlighter=function() {this.noGutter=false;this.addControls=true;this.collapse=false;this.tabsToSpaces=true;this.wrapColumn=80;this.showColumns=true;} dp.sh.Highlighter.SortCallback=function(m1,m2) {if(m1.indexm2.index) return 1;else {if(m1.lengthm2.length) return 1;} return 0;} dp.sh.Highlighter.prototype.CreateElement=function(name) {var result=document.createElement(name);result.highlighter=this;return result;} dp.sh.Highlighter.prototype.GetMatches=function(regex,css) {var index=0;var match=null;while((match=regex.exec(this.code))!=null) this.matches[this.matches.length]=new dp.sh.Match(match[0],match.index,css);} dp.sh.Highlighter.prototype.AddBit=function(str,css) {if(str==null||str.length==0) return;var span=this.CreateElement('SPAN');str=str.replace(/ /g,' ');str=str.replace(/');if(css!=null) {if((/br/gi).test(str)) {var lines=str.split(' 
');for(var i=0;ic.index)&&(match.index/gi,'\n');var lines=html.split('\n');if(this.addControls==true) this.bar.appendChild(dp.sh.Toolbar.Create(this));if(this.showColumns) {var div=this.CreateElement('div');var columns=this.CreateElement('div');var showEvery=10;var i=1;while(i<=150) {if(i%showEvery==0) {div.innerHTML+=i;i+=(i+'').length;} else {div.innerHTML+='·';i++;}} columns.className='columns';columns.appendChild(div);this.bar.appendChild(columns);} for(var i=0,lineIndex=this.firstLine;i0;i++) {if(Trim(lines[i]).length==0) continue;var matches=regex.exec(lines[i]);if(matches!=null&&matches.length>0) min=Math.min(matches[0].length,min);} if(min>0) for(var i=0;i

Blogger Syntax Highliter

Version: {V}

http://www.dreamprojections.com/syntaxhighlighter

©2004-2007 Alex Gorbatchev.

'},ClipboardSwf:null,Version:'1.5.1'}};dp.SyntaxHighlighter=dp.sh;dp.sh.Toolbar.Commands={ExpandSource:{label:'+ expand source',check:function(highlighter){return highlighter.collapse;},func:function(sender,highlighter) {sender.parentNode.removeChild(sender);highlighter.div.className=highlighter.div.className.replace('collapsed','');}},ViewSource:{label:'view plain',func:function(sender,highlighter) {var code=dp.sh.Utils.FixForBlogger(highlighter.originalCode).replace(/'+code+'');wnd.document.close();}},CopyToClipboard:{label:'copy to clipboard',check:function(){return window.clipboardData!=null||dp.sh.ClipboardSwf!=null;},func:function(sender,highlighter) {var code=dp.sh.Utils.FixForBlogger(highlighter.originalCode).replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');if(window.clipboardData) {window.clipboardData.setData('text',code);} else if(dp.sh.ClipboardSwf!=null) {var flashcopier=highlighter.flashCopier;if(flashcopier==null) {flashcopier=document.createElement('div');highlighter.flashCopier=flashcopier;highlighter.div.appendChild(flashcopier);} flashcopier.innerHTML='';} alert('The code is in your clipboard now');}},PrintSource:{label:'print',func:function(sender,highlighter) {var iframe=document.createElement('IFRAME');var doc=null;iframe.style.cssText='position:absolute;width:0px;height:0px;left:-500px;top:-500px;';document.body.appendChild(iframe);doc=iframe.contentWindow.document;dp.sh.Utils.CopyStyles(doc,window.document);doc.write('

'+highlighter.div.innerHTML+'

');doc.close();iframe.contentWindow.focus();iframe.contentWindow.print();alert('Printing...');document.body.removeChild(iframe);}},About:{label:'?',func:function(highlighter) {var wnd=window.open('','_blank','dialog,width=300,height=150,scrollbars=0');var doc=wnd.document;dp.sh.Utils.CopyStyles(doc,window.document);doc.write(dp.sh.Strings.AboutDialog.replace('{V}',dp.sh.Version));doc.close();wnd.focus();}}};dp.sh.Toolbar.Create=function(highlighter) {var div=document.createElement('DIV');div.className='tools';for(var name in dp.sh.Toolbar.Commands) {var cmd=dp.sh.Toolbar.Commands[name];if(cmd.check!=null&&!cmd.check(highlighter)) continue;div.innerHTML+=''+cmd.label+'';} return div;} dp.sh.Toolbar.Command=function(name,sender) {var n=sender;while(n!=null&&n.className.indexOf('dp-highlighter')==-1) n=n.parentNode;if(n!=null) dp.sh.Toolbar.Commands[name].func(sender,n.highlighter);} dp.sh.Utils.CopyStyles=function(destDoc,sourceDoc) {var links=sourceDoc.getElementsByTagName('link');for(var i=0;i');} dp.sh.Utils.FixForBlogger=function(str) {return(dp.sh.isBloggerMode==true)?str.replace(/
|<br\s*\/?>/gi,'\n'):str;} dp.sh.RegexLib={MultiLineCComments:new RegExp('/\\*[\\s\\S]*?\\*/','gm'),SingleLineCComments:new RegExp('//.*$','gm'),SingleLinePerlComments:new RegExp('#.*$','gm'),DoubleQuotedString:new RegExp('"(?:\\.|(\\\\\\")|[^\\""\\n])*"','g'),SingleQuotedString:new RegExp("'(?:\\.|(\\\\\\')|[^\\''\\n])*'",'g')};dp.sh.Match=function(value,index,css) {this.value=value;this.index=index;this.length=value.length;this.css=css;} dp.sh.Highlighter=function() {this.noGutter=false;this.addControls=true;this.collapse=false;this.tabsToSpaces=true;this.wrapColumn=80;this.showColumns=true;} dp.sh.Highlighter.SortCallback=function(m1,m2) {if(m1.indexm2.index) return 1;else {if(m1.lengthm2.length) return 1;} return 0;} dp.sh.Highlighter.prototype.CreateElement=function(name) {var result=document.createElement(name);result.highlighter=this;return result;} dp.sh.Highlighter.prototype.GetMatches=function(regex,css) {var index=0;var match=null;while((match=regex.exec(this.code))!=null) this.matches[this.matches.length]=new dp.sh.Match(match[0],match.index,css);} dp.sh.Highlighter.prototype.AddBit=function(str,css) {if(str==null||str.length==0) return;var span=this.CreateElement('SPAN');str=str.replace(/ /g,' ');str=str.replace(/');if(css!=null) {if((/br/gi).test(str)) {var lines=str.split(' 
');for(var i=0;ic.index)&&(match.index/gi,'\n');var lines=html.split('\n');if(this.addControls==true) this.bar.appendChild(dp.sh.Toolbar.Create(this));if(this.showColumns) {var div=this.CreateElement('div');var columns=this.CreateElement('div');var showEvery=10;var i=1;while(i<=150) {if(i%showEvery==0) {div.innerHTML+=i;i+=(i+'').length;} else {div.innerHTML+='·';i++;}} columns.className='columns';columns.appendChild(div);this.bar.appendChild(columns);} for(var i=0,lineIndex=this.firstLine;i0;i++) {if(Trim(lines[i]).length==0) continue;var matches=regex.exec(lines[i]);if(matches!=null&&matches.length>0) min=Math.min(matches[0].length,min);} if(min>0) for(var i=0;i

ページビューの合計