码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-02-09 14:13:27      阅读:1633      评论:0      收藏:0      [点我收藏+]

标签:android   asynctask   notificationmanager   notificationcompat   httpurlconnection   

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;
}

@Override
protected 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() {
@Override
public 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;
}

@Override
protected void onPreExecute() {
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContentTitle("APP文件下载")
.setContentText("正在APP文件...")
.setSmallIcon(R.drawable.ic_launcher);
}

@Override
protected 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("http://www.abc.2015/01/31/20150131140339351%E5%8D%83%E5%8D%92%E4%BF%9D%E8%BD%A6.apk");
}else {
Toast.makeText(this,"无可用的网络!",Toast.LENGTH_LONG).show();
}
}

技术分享

技术分享

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

标签:android   asynctask   notificationmanager   notificationcompat   httpurlconnection   

原文地址:http://blog.csdn.net/tianyiii/article/details/43669325

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!