通过异步任务下载并安装Apk:
一、MainActivity 区块:
public class MainActivity extends Activity implements CallBack {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//点击,下载apk
public void downloadApk(View view){
//启动异步任务下载
DownloadTask task = new DownloadTask(this);
task.execute("http://www.ytmfdw.com/download/puzzle_v1.0.0.apk");
}
ProgressDialog pd;
@Override
public void start() {
//初始化进度对话框 并显示
if(pd==null){
pd = new ProgressDialog(this);
pd.setTitle("下载进度");
pd.setMessage("正在下载,请稍后……");
pd.setIndeterminate(false);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(false);
}
//显示
pd.show();
}
@Override
public void publish(int progess) {
//更新进度条对话框的进度
pd.setProgress(progess);
}
@Override
public void finish(String apkPath) {
pd.dismiss();
installApk(apkPath);
}
/**
* 安装apk
*
* @param url
*/
private void installApk(String apkFilePath) {
File apkfile = new File(apkFilePath);
if (!apkfile.exists()) {
return;
}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
"application/vnd.android.package-archive");
startActivity(i);
}
}
二、 异步任务---下载Apk区块:
public class DownloadTask extends AsyncTask<String, Integer, String> {
//接口回调
public interface CallBack{
//开始下载时 调用
public void start();
//发布进度调用
public void publish(int progess);
//结束调用调用
public void finish(String apkPath);
}
CallBack cb;
public DownloadTask(CallBack cb) {
super();
this.cb = cb;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if(cb!=null){
cb.start();
}
}
@Override
protected String doInBackground(String... params) {
//1、网址
String http = params[0];
//2、HttpUrlConnection
HttpURLConnection conn = null;
File resulet=null;
//3、Url url
try {
URL url = new URL(http);
//4.url.openConnection
conn = (HttpURLConnection) url.openConnection();
//5.通过url.openConnection获取 流的总长度
int total = conn.getContentLength();
//6.获取文件的InputStream,outputStream
InputStream in = conn.getInputStream();
String fileName = http.substring(http.lastIndexOf("/")+1);
File dir = Environment.getExternalStorageDirectory();
resulet =new File(dir, fileName);
FileOutputStream out = new FileOutputStream(resulet);
//7.inputStream-->outputStream
byte[] buffer = new byte[2048];
int len = 0;
int sumByte = 0;
while((len = in.read(buffer))!= -1){
out.write(buffer, 0, len);
//累加已读字节
sumByte = sumByte+len;
//计算百分比
int per = (int) (sumByte*100f/total);
//发布进度条
publishProgress(per);
}
//刷出缓冲
out.flush();
//8.关闭流
out.close();
in.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(conn!=null){
conn.disconnect();
}
}
//9.得到返回保存的文件的路径
if(resulet==null){
return null;
}
return resulet.getAbsolutePath();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if(cb != null){
cb.publish(values[0]);
}
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//下载完成,开始安装apk
if(cb!=null){
cb.finish(result);
}
}
}
三:布局代码快:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="downloadApk"
android:text="下载并安装apk" />
</RelativeLayout>