Android学习笔记19:带有通知栏的进度条的Android下载文件

1、首先,android的文件下载需要以下几个权限:

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

2、因为文件下载是一个长时间的任务,不能在UI线程中更新,,需要另外开辟一个新的线程来进行下载的工作,在这里我们用Android封装的异步任务类——AsyncTask,这个类来完成一些长时间进行的工作:

private class DownloadAppTask extends AsyncTask<String, Integer, Boolean> {private int RESULT_OK = 200;private int PROGRESS_ID = 1;private Context context;private NotificationManager manager;private NotificationCompat.Builder mBuilder;private int size = 0;private int max;public DownloadAppTask (Context context){this.context = context;}@Overrideprotected Boolean doInBackground(String… params) {try {return downloadUrl(params[0]);} catch (IOException e) {return false;}}private boolean downloadUrl(String myurl) throws IOException {InputStream is = null;OutputStream os = null;URL url = new URL(myurl);HttpURLConnection conn = (HttpURLConnection)url.openConnection();conn.setReadTimeout(10000);conn.setConnectTimeout(15000);conn.setRequestMethod("GET");conn.setDoInput(true);conn.connect();int code = conn.getResponseCode();url = null;if(code==RESULT_OK) {max = 0;is = conn.getInputStream();File file = new File(Environment.getExternalStorageDirectory(),"/app");if(!file.exists()) {file.mkdir();}final File f = new File(file.getAbsolutePath(),"myapp.apk");os = new FileOutputStream(f);byte[] buffer = new byte[1000];max = conn.getContentLength();new Thread(new Runnable() {@Overridepublic void run() {while (max>size) {try {publishProgress(size);Thread.sleep(1000);} catch (InterruptedException e) {}}publishProgress(max);installApp(f);}}).start();int len;while ((len = is.read(buffer))!=-1) {os.write(buffer,0,len);size = size + len;}os.flush();os.close();is.close();conn = null;file = null;return true;}return false;}@Overrideprotected void onPreExecute() {manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);mBuilder = new NotificationCompat.Builder(context);mBuilder.setContentTitle("APP文件下载").setContentText("正在APP文件…").setSmallIcon(R.drawable.ic_launcher);}@Overrideprotected void onProgressUpdate(Integer… values) {if(max<=values[0]) {mBuilder.setContentText("APP文件下载完成!");mBuilder.setProgress(0, 0, false);}else {mBuilder.setProgress(max, values[0], false);}manager.notify(PROGRESS_ID,mBuilder.build());}//文件下载完成安装应用private void installApp(File file) {Intent intent = new Intent(Intent.ACTION_VIEW);intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");startActivity(intent);}}

3、在主线程中调用一下方法即可:

判断网络是否可用,然后执行进行下载

private void myClickHandler(){ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo networkInfo = manager.getActiveNetworkInfo();if(networkInfo!=null&&networkInfo.isConnected()) {DownloadAppTask task = new DownloadAppTask(this);task.execute("%E5%8D%83%E5%8D%92%E4%BF%9D%E8%BD%A6.apk");}else {Toast.makeText(this,"无可用的网络!",Toast.LENGTH_LONG).show();}}

在人生的大海中,我们虽然不能把握风的大小,却可以调整帆的方向。

Android学习笔记19:带有通知栏的进度条的Android下载文件

相关文章:

你感兴趣的文章:

标签云: