使用DownloadManager实现文件下载



创建一个新工程LearnDownLoad

 

androidManifest.xml文件中添加网络访问权限和sd读写权限

 

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.INTERNET" />

 

activity_main.xml仅放一个按钮

<Button     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="使用下载管理器下载"     android:id="@+id/btnDownloadMG"     android:onClick="downloadByManager"     android:layout_centerHorizontal="true"     android:layout_marginTop="68dp" />

 

MainActivity.java代码
package com.czg.com.learndownload; import android.app.DownloadManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.webkit.MimeTypeMap; import android.webkit.URLUtil; import android.widget.Button; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class MainActivity extends AppCompatActivity {     String myHTTPUrl="http://192.168.1.104:81/userPhp/music/backstreeboy.mp3";     //String myHTTPUrl="http://192.168.1.104:81/userPhp/download/1234.png";     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);     } //通过系统下载管理器下载      public void downloadByManager(View view) {         DownloadManager.Request request=new DownloadManager.Request(Uri.parse(myHTTPUrl));         request.setTitle("下载文件.");         request.setDescription("文件下载中...");         //request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);         request.allowScanningByMediaScanner();         request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION);         String nameOfFile=URLUtil.guessFileName(myHTTPUrl,null,                 MimeTypeMap.getFileExtensionFromUrl(myHTTPUrl));         request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,nameOfFile);         DownloadManager manager= (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);         manager.enqueue(request);     } }
源码下载地址:https://yunpan.cn/crx5tevgZtTcz  访问密码 6bbf

你可能感兴趣的:(文件下载,DownloadManager)