在androi中,volley适合小文件的获取和大并发,如果支持大文件的下载可以用Android原生的DownloadManager。DownloadManager默认支持多线程下载、断点续传等。
基础代码如下:
public class MainActivity extends Activity { private DownloadManager manager ; private DownloadCompleteReceiver receiver; private Button downBtn ; private Context mContext; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = this; //获取下载服务 IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE); receiver = new DownloadCompleteReceiver(); registerReceiver(receiver, filter); downBtn = (Button)findViewById(R.id.button1); downBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { //创建下载请求 DownloadManager.Request request = new DownloadManager.Request( Uri.parse("http://www.bz55.com/uploads/allimg/110807/2019341501-0.jpg")); request.setAllowedNetworkTypes(Request.NETWORK_WIFI); //定义notification提示 request.setNotificationVisibility(Request.VISIBILITY_VISIBLE); request.setTitle("下载"); request.setDescription("壁纸正在下载"); //在onclick中无法直接通过this取到Context上下文 request.setDestinationInExternalFilesDir(mContext, null, "test_download"); manager =(DownloadManager)getSystemService(DOWNLOAD_SERVICE); manager.enqueue(request); } }); } //接受下载完成后的intent class DownloadCompleteReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){ Toast.makeText(context, "download complete", Toast.LENGTH_SHORT).show(); } } } @Override protected void onDestroy() { if(receiver != null){ unregisterReceiver(receiver); } super.onDestroy(); } }