2015-06-29 34 views
-2

我使用此代碼從URL下載鏈接,並保存到SD卡(蒙山智能手機)安卓:startActivity(意向)內部消除打開的瀏覽器

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://yourname.com/file.mp3")); 
startActivity(intent); 

但啓動這一意圖,瀏覽器打開後下載鏈接

如何在不打開瀏覽器的情況下從網址下載?

+0

最好的回答你的問題 [http://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-the-progress-in-a- progressdialog] [1] –

回答

1

如果你想在後臺,然後使用DownloadManager下載,因爲使用意圖將在前臺總是啓動瀏覽器。使用下載管理器的簡單教程

http://blog.vogella.com/2011/06/14/android-downloadmanager-example/ 

或者你也可以看看這裏

http://www.compiletimeerror.com/2013/11/download-manager-in-android-with-example.html#.VZDtUfmqqko 
+0

Thx,如何導入DownloadManager進入庫? – user3612383

+0

你並不需要導入下載管理圖書館,只是用它在你的源代碼 –

+0

我用這個代碼,但錯誤:下載管理器不能被解析爲一個類型 – user3612383

0

試試這個代碼發生在你的Activity這個功能和自動傳遞所需的參數和該功能啓動下載過程,並保存後,此功能會將您下載的文件恢復爲FILE。

public File downloadFile(Context context, String url, String filename) { 
      File direct = new File(Environment.getExternalStorageDirectory() + "/" + "Your_Foldername"); 

      if (!direct.exists()) { 
       direct.mkdirs(); 
      } else { 
       File file = new File(Environment.getExternalStorageDirectory() + "/" + "Your_Foldername" + "/" + filename); 
       if(file.exists()) 
       file.delete(); 
      } 

      DownloadManager mgr = (DownloadManager) context.getApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE); 

      Uri downloadUri = Uri.parse(url); 
      DownloadManager.Request request = new DownloadManager.Request(downloadUri); 

      request.setAllowedNetworkTypes(
        DownloadManager.Request.NETWORK_WIFI 
          | DownloadManager.Request.NETWORK_MOBILE) 
        .setAllowedOverRoaming(false).setTitle(context.getResources().getString(R.string.app_name)) 
        .setDescription("Downloading Share Image for " + context.getResources().getString(R.string.app_name)) 
        .setDestinationInExternalPublicDir("/" + "Your_Foldername", filename); 

      mgr.enqueue(request); 
      return direct; 
     }