参考《Professional Android 4 Development》
使用Internet资源
打开URI
String myFeed = getString(R.string.my_feed); try { URL url = new URL(myFeed); // Create a new HTTP URL connection URLConnection connection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection)connection; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream in = httpConnection.getInputStream(); processStream(in); } }catch (MalformedURLException e) { Log.d(TAG, “Malformed URL Exception.”); }catch (IOException e) { Log.d(TAG, “IO Exception.”); }
使用Download Manager
Download Manager是一个系统服务,可以这样获取:
String serviceString = Context.DOWNLOAD_SERVICE;
DownloadManager downloadManager;
downloadManager = (DownloadManager)getSystemService(serviceString);
开始下载
下载实际是将一个Download请求加入到下载队列的过程:
String serviceString = Context.DOWNLOAD_SERVICE; DownloadManager downloadManager; downloadManager = (DownloadManager)getSystemService(serviceString); Uri uri = Uri.parse(“http://developer.android.com/shareables/icon_templates-v4.0.zip”); DownloadManager.Request request = new Request(uri); long reference = downloadManager.enqueue(request);
设置“限Wifi条件下下载”:
request.setAllowedNetworkTypes(Request.NETWORK_WIFI);
下载结束
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE); BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); if (myDownloadReference == reference) { // Do something with downloaded file. } } };
registerReceiver(receiver, filter);
修改下载文件夹
以写入SD卡为例,首先要获得写SD卡的权限:
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/>
设置存储路径:
request.setDestinationUri(Uri.fromFile(f));
存储文件:
request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, “Bugdroid.png”);
取消或删除下载:
downloadManager.remove(REFERENCE_1, REFERENCE_2, REFERENCE_3);
获取下载信息
@Override public void onReceive(Context context, Intent intent) { long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); if (reference == myDownloadReference) { Query myDownloadQuery = new Query(); myDownloadQuery.setFilterById(reference); Cursor myDownload = downloadManager.query(myDownloadQuery); if (myDownload.moveToFirst()) { int fileNameIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME); int fileUriIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI); String fileName = myDownload.getString(fileNameIdx); String fileUri = myDownload.getString(fileUriIdx); // TODO Do something with the file. } myDownload.close(); } }