Загрузка файла не работает в Android с помощью cordova-2.9.0
Я работаю над приложением Hybird, и это кажется очень простым способом загрузить файл pdf с сервера с использованием атрибута загрузки якоря HTML5, и это работает точно так, как и ожидалось, используя приведенный ниже код в настольных браузерах.
<a href="/path/sample.pdf" download="Test.pdf">Download</a>
Проблема: Но когда я пытаюсь запустить тот же код в моем приложении Hybird, используя cordova 2.9.0, при отладке приложения на мобильном устройстве; при нажатии Download ничего не появляется и загрузка не начинается.
Я что-то здесь упускаю?
Пожалуйста, предложите.
1 ответ
Этот код для платформы Android. Сначала откройте файл [appname].java
в папке вашей платформы:appname\platforms\android\src\com\[appname]\app
Затем установите downloadListener для веб-просмотра сразу после super.init();
вот полный код:
package com.[appname].app;
import android.os.Bundle;
import org.apache.cordova.*;
public class [appname] extends CordovaActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.init();
super.appView.setDownloadListener(new android.webkit.DownloadListener() {
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
android.util.Log.d("Logger","url : " + url + " userAgent: " + userAgent + " contentDisposition: " + contentDisposition + " mimeType: " + mimetype + " contentLength " + contentLength);
android.net.Uri source = android.net.Uri.parse(url);
// Make a new request
android.app.DownloadManager.Request request = new android.app.DownloadManager.Request(source);
// appears the same in Notification bar while downloading
String filename = getFilename(contentDisposition);
request.setDescription("This file will be saved in your downloads folder.");
request.setTitle(filename);
//add cookie on request header (for authenticated web app)
String cookieContent = getCookieFromAppCookieManager(source.getHost());
request.addRequestHeader("Cookie", cookieContent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
// save the file in the "Downloads" folder of SDCARD
request.setDestinationInExternalPublicDir(android.os.Environment.DIRECTORY_DOWNLOADS, filename);
// get download service and enqueue file
android.app.DownloadManager manager = (android.app.DownloadManager) getSystemService(android.content.Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
});
super.loadUrl(Config.getStartUrl());
//super.loadUrl("file:///android_asset/www/index.html");
};
public String getFilename(String contentDisposition){
String filename[] = contentDisposition.split("filename=");
return filename[1].replace("filename=", "").replace("\"", "").trim();
};
public String getCookieFromAppCookieManager(String url){
android.webkit.CookieManager cookieManager = android.webkit.CookieManager.getInstance();
if (cookieManager == null)
return null;
String rawCookieHeader = null;
// Extract Set-Cookie header value from Android app CookieManager for this URL
rawCookieHeader = cookieManager.getCookie(url);
if (rawCookieHeader == null)
return null;
return rawCookieHeader;
};
}