0

My android app would have a link on it to a server that is hosting a file. I would like my app to download this file from the server in the background, so that the user can keep the app in focus and continue doing what he wants to do.

I assume that AsyncTask can be used to do this in background. The link in the app is to a php page, which has the following code -

header("Content-type: application/xls");
header("Content-Disposition: attachment; filename=\myFile.xls\"");
readfile("myFile.xls"); 

From what I understand, the readfile() will get data from the server, and then write it into its buffer. And the AsyncTask would read from this buffer and store it into the location in the phone as specified.

My question - 1. Do let me know if my approach is correct (what I have described above) 2. I assume that the header("Content-Disposition: ..) will result in a OPEN/SAVE Dialog box (as in the case of normal desktop browser dialog box). Will similar dialog box be displayed when the link is called by an android app as well? If yes, is there someway to not show this dialog box and instead just download, so that the user need not bother where the file is getting stored in his phone?

Thanks!

4

1 に答える 1

1

非同期タスクでは、これをバックグラウンドで実行します。PHPページは、xmlファイルの内容を返します。を使用 HttpGetしてコンテンツを取得し、選択した場所に保存します。

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet ("http://urltopage.com/page");

HttpResponse response = httpclient.execute(httpget);
sb = new StringBuffer("");
in = new BufferedReader(new InputStreamReader(response
                        .getEntity().getContent()));

String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
    sb.append(line + NL);

}
in.close();

次に、テキスト形式のコンテンツでやりたいことができます。文字列ビルダーは必須ではありませんが、そうすればきれいな文字列が得られます。文字列を作成する代わりに、すぐにファイルに書き込むことができると思います。

ファイルに直接入れたい場合:

FileOutputStream fos = new FileOutputStream(newFile("\path to file"));

byte[] buff = new byte[4096];
int len; 
while((len = in.read(buff)) > 0) {
      fos.write(buff, 0, len);
}


fos.close()
于 2013-02-16T19:35:03.100 に答える