[英]Download Manager with Google Drive URL
我正在嘗試使用 android DownloadManager 下載存儲在 Google Drive 中的文件。
我從 Google 獲得了登錄令牌,如下所示:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(AppConfig.getInstance().get("google_client_id"))
.requestProfile()
.requestEmail()
.build();
我收到一個帶有谷歌驅動器文件 url 的通知,我將它傳遞給 DownloadManager,將令牌傳遞給它:
String cookie = CookieManager.getInstance().getCookie(d.getURL());
request.addRequestHeader("Cookie",cookie);
request.addRequestHeader("Authorization", "OAuth " + profile.getToken());
//d is the document object, that contains url, file name, etcc
//Profile is a simple object class that hold the user data taken from sign Google, like token, name, email, etcc
使用簡單的廣播接收器來管理下載結果(ACTION_DOWNLOAD_COMPLETE)。
下載已成功完成,但文件已損壞。 如果我嘗試打開它,設備(和電腦)會給我一個格式錯誤。 該文件包含一個 Google 頁面的 HTML 代碼,該代碼表明存在錯誤,僅此而已。
(我使用的帳戶已啟用以讀取和下載來自此特定驅動器存儲的文檔)
這是使用 DownloadManager 下載 Google Drive 文件的正確方法嗎? 有可能這樣做嗎?
您也可以通過此方法從 google 下載文件
參考此 Url
https://drive.google.com/uc?id=<FILE_ID>&export=download
將<FILE_ID>
替換為您的可共享文件 ID。
此外,您可以從此解決方案中獲得幫助下載帶有 Android 的文件,並在 ProgressDialog 中顯示進度
您可以使用其中的 doInBackground function 來解決您的查詢。
試試這是否有幫助...
正如@saddamkamal 的回答,使用Google Drive
下載URL
。
AsyncTask.execute(new Runnable() {
@Override
public void run() {
DownloadManager downloadmanager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("https://drive.google.com/uc?id=<FILE_ID>&export=download");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle("My File");
request.setDescription("Downloading");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "file.extension");
downloadmanager.enqueue(request);
}
});
由於文件已下載。 檢查 Google 驅動器和 android 中文件的大小。 然后確保您的文件擴展名是正確的。 因為文件擴展名可能不存在,android 會將其視為二進制文件。 現在您的文件擴展名為 android。 安裝適當的應用程序以打開它。 這是更新的代碼
public class MainActivity extends AppCompatActivity {
private Button btn_download;
private long downloadID;
// using broadcast method
private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//Fetching the download id received with the broadcast
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
//Checking if the received broadcast is for our enqueued download by matching download id
if (downloadID == id) {
Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_download = findViewById(R.id.download_btn);
// using broadcast method
registerReceiver(onDownloadComplete,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
beginDownload();
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
// using broadcast method
unregisterReceiver(onDownloadComplete);
}
private void beginDownload(){
String url = "http://speedtest.ftp.otenet.gr/files/test10Mb.db";
String fileName = url.substring(url.lastIndexOf('/') + 1);
fileName = fileName.substring(0,1).toUpperCase() + fileName.substring(1);
File file = Util.createDocumentFile(fileName, context);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url))
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN)// Visibility of the download Notification
.setDestinationUri(Uri.fromFile(file))// Uri of the destination file
.setTitle(fileName)// Title of the Download Notification
.setDescription("Downloading")// Description of the Download Notification
.setRequiresCharging(false)// Set if charging is required to begin the download
.setAllowedOverMetered(true)// Set if download is allowed on Mobile network
.setAllowedOverRoaming(true);// Set if download is allowed on roaming network
DownloadManager downloadManager= (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadID = downloadManager.enqueue(request);// enqueue puts the download request in the queue.
// using query method
boolean finishDownload = false;
int progress;
while (!finishDownload) {
Cursor cursor = downloadManager.query(new DownloadManager.Query().setFilterById(downloadID));
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (status) {
case DownloadManager.STATUS_FAILED: {
finishDownload = true;
break;
}
case DownloadManager.STATUS_PAUSED:
break;
case DownloadManager.STATUS_PENDING:
break;
case DownloadManager.STATUS_RUNNING: {
final long total = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
if (total >= 0) {
final long downloaded = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
progress = (int) ((downloaded * 100L) / total);
// if you use downloadmanger in async task, here you can use like this to display progress.
// Don't forget to do the division in long to get more digits rather than double.
// publishProgress((int) ((downloaded * 100L) / total));
}
break;
}
case DownloadManager.STATUS_SUCCESSFUL: {
progress = 100;
// if you use aysnc task
// publishProgress(100);
finishDownload = true;
Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
break;
}
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.