Android AsyncTask软件升级
Urls.java
public static final String APP_DOWNLOAD_URL = "下载地址";
dialog_update_download_progress.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView android:id="@+id/progressTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/white"
/>
<ProgressBar android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
ApplicationVersion.java
import android.os.Parcel;
import android.os.Parcelable;
public class ApplicationVersion implements Parcelable {
private int id;
private int version_code;//必须
private String type;
private String version_name;
private String application_name;//必须
private String update_date;
private String path;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getVersion_code() {
return version_code;
}
public void setVersion_code(int version_code) {
this.version_code = version_code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getVersion_name() {
return version_name;
}
public void setVersion_name(String version_name) {
this.version_name = version_name;
}
public String getApplication_name() {
return application_name;
}
public void setApplication_name(String application_name) {
this.application_name = application_name;
}
public String getUpdate_date() {
return update_date;
}
public void setUpdate_date(String update_date) {
this.update_date = update_date;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public static final Parcelable.Creator<ApplicationVersion> CREATOR=new Creator<ApplicationVersion>() {
@Override
public ApplicationVersion createFromParcel(Parcel source) {
return new ApplicationVersion(source);
}
@Override
public ApplicationVersion[] newArray(int size) {
return new ApplicationVersion[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeInt(version_code);
dest.writeString(type);
dest.writeString(version_name);
dest.writeString(application_name);
dest.writeString(update_date);
dest.writeString(path);
}
public ApplicationVersion(Parcel source){
id=source.readInt();
version_code=source.readInt();
type=source.readString();
version_name=source.readString();
application_name=source.readString();
update_date=source.readString();
path=source.readString();
}
public ApplicationVersion() {
// TODO Auto-generated constructor stub
}
}
CheckUpdateActivity.java
UpdateActionTask asynTask=new UpdateActionTask(CheckUpdateActivity.this, (ApplicationVersion)appVersion);
asynTask.execute(10);
AndroidUtil.java
public class AndroidUtil {
/**
* 检测是否存在SD卡
* @param mContext
* @return
*/
public static boolean checkSdCard(){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
return true;
}else{
return false;
}
}
/**
* 获取本地apk的版本信息
* @param context
* @return
*/
public static int getCurrentVerCode(Context context){
int version=-1;
try {
PackageInfo pi=context.getPackageManager().getPackageInfo(context.getApplicationContext().getPackageName(), 0);
version=pi.versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return version;
}
/**
* 获取本地apk的版本名称
* @param context
* @return
*/
public static String getCurrentVerName(Context context){
String version=null;
try {
PackageInfo pi=context.getPackageManager().getPackageInfo(context.getApplicationContext().getPackageName(), 0);
version=pi.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return version;
}
}
UriConstants.java
public class UriConstants {
//存储卡根目录
public static final String _XXX="/xxx";
//更新文件目录
public static final String _UPDATE="/update";
/**
* 获取更新文件保存路径
* @return
*/
public static String getUpdateDir(){
String path=null;
if(AndroidUtil.checkSdCard()){
path=Environment.getExternalStorageDirectory().toString()+XXX+_UPDATE;
}
return path;
}
}
UpdateActionTask.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
/**
* 异步更新软件
* @author
*
*/
public class UpdateActionTask extends BaseAsyncTask {
private static final String savePath=UriConstants.getUpdateDir();
private String fileName;
//进度条
private ProgressBar progressBar;
private TextView textView;
//下载弹出框
private AlertDialog downloadDialog;
//APK更新的详细信息
private ApplicationVersion apkInfo;
//是否取消下载
private boolean interceptFlag=false;
//是否存在SD卡
private boolean sdExists=false;
public UpdateActionTask(Context mContext,ApplicationVersion apkInfo){
super(mContext);
this.apkInfo=apkInfo;
if(apkInfo!=null){
fileName=savePath+File.separator+apkInfo.getApplication_name();
}
}
public boolean checkURL(String url){
try{
URL mUrl=new URL(url);
HttpURLConnection urlConn=(HttpURLConnection)mUrl.openConnection();
urlConn.connect();
if(urlConn.getResponseCode()==HttpURLConnection.HTTP_OK){
return true;
}
}catch(Exception e){
e.printStackTrace();
return false;
}
return false;
}
@Override
protected void onPostExecute(String result) {
if(downloadDialog!=null){
downloadDialog.dismiss();
}
if (sdExists) {
if(!interceptFlag && RESULT_SUCCESS.equals(result)){
installApk();
}else if(RESULT_FAIL.equals(result)){
AndroidUtil.toastTextLong(context, "更新失败.");
}
}else {
AlertDialog dialog;
AlertDialog.Builder builder =new AlertDialog.Builder(context)
.setTitle("提示")
.setMessage("检测到手机没有存储卡,是否打开浏览器下载?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Uri uri = Uri.parse(Urls.APP_DOWNLOAD_URL);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(intent);
arg0.dismiss();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}
});
dialog=builder.create();
dialog.show();
}
super.onPostExecute(result);
}
@Override
protected void onPreExecute() {
if(AndroidUtil.checkSdCard()){
if(apkInfo==null){
AndroidUtil.toastTextLong(context, "更新失败.");
cancel(true);
return;
}
File file=new File(savePath);
if(!file.exists()){
file.mkdirs();
}
sdExists=true;
showDownloadDialog();
}else{
sdExists=false;
}
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
int pro=values[0];
progressBar.setProgress(pro);
textView.setText("进度: "+pro+"%");
super.onProgressUpdate(values);
}
@Override
protected String doInBackground(Integer... params) {
String result="";
if(apkInfo==null){
result=RESULT_FAIL;
}else if(!checkURL(Urls.APP_DOWNLOAD_URL)){
//检测APK下载地址是否可用
result=RESULT_FAIL;
}else if(apkInfo!=null && sdExists){
InputStream ins=null;
FileOutputStream fos=null;
File file=new File(savePath);
if(!file.exists()){
file.mkdirs();
}
try{
URL url=new URL(Urls.APP_DOWNLOAD_URL);
URLConnection urlConn=url.openConnection();
ins=urlConn.getInputStream();
int length=urlConn.getContentLength();
fos=new FileOutputStream(fileName);
int count=0;
int numRead=0;
byte[] buf=new byte[1024];
while(!interceptFlag && (numRead=ins.read(buf))!=-1){
count+=numRead;
int progressCount=(int)(((float)count/length)*100);
publishProgress(progressCount);
fos.write(buf, 0, numRead);
}
fos.flush();
result=RESULT_SUCCESS;
}catch(Exception e){
e.printStackTrace();
result=RESULT_FAIL;
}finally{
try {
if(fos!=null){
fos.close();
}
if(ins!=null){
ins.close();
}
} catch (IOException e) {
e.printStackTrace();
result=RESULT_FAIL;
}
}
}
return result;
}
/**
* 弹出下载对话框
*/
private void showDownloadDialog(){
Builder builder=new AlertDialog.Builder(context);
builder.setTitle("正在更新版本");
builder.setCancelable(false);
final LayoutInflater inflater=LayoutInflater.from(context);
View view=inflater.inflate(R.layout.dialog_update_download_progress, null);
textView=(TextView)view.findViewById(R.id.progressTv);
textView.setText("进度: 0");
progressBar=(ProgressBar)view.findViewById(R.id.progressBar);
builder.setView(view);
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
interceptFlag=true;
}
});
downloadDialog=builder.create();
downloadDialog.show();
}
/**
* 安装apk
*/
private void installApk(){
File file=new File(fileName);
if(!file.exists()){
Log.e("-------------软件更新之安装应用--------------", "找不到下载的应用");
return;
}
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
context.startActivity(intent);
}
}
BaseAsyncTask .java
import android.content.Context;
import android.os.AsyncTask;
/**
*
* @author
*
* 异步线程原型
* AsyncTask<Params, Progress, Result>
*/
public class BaseAsyncTask extends AsyncTask<Integer, Integer, String>{
public static final String RESULT_SUCCESS="success";
public static final String RESULT_FAIL="fail";
protected Context context;
public BaseAsyncTask(Context context){
this.context=context;
}
@Override
protected String doInBackground(Integer... params) {
return null;
}
}