android流程:服务端部署一个服务,返回最新的app信息(用json描述)。
app思路:
程序启动检查版本:
1:取本地版本和请求服务端app信息,使用volly库请求服务并且解析成json对象。如果服务端版本大于本地,提示信息让用户选择是否更新。
2:如果忽略,那么关闭对话框。
3:如果选择更新。那么流程如下:
1:下载完成启动安装
2:中途取消。
package com.example.autoupdate_android;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.media.MediaDescriptionCompatApi21.Builder;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
public class UpdateManager {
private static final String PATH="http://xxx/test/versiontest.txt";
private Dialog mDownLoadDialog;
private String mSavePath="";
private int CurrentProgress;
private ProgressBar process1;
private static final int DOWNLOAD_ING=1;
private static final int DOWNLOAD_OK=2;
private static boolean IsCancelDownLoad=false;
private Handler mUpdateProgressHandler=new Handler(){
public void handleMessage(Message msg)
{
//1:正在下载
//2:下载完成
switch(msg.what)
{
case DOWNLOAD_ING:
process1.setProgress(CurrentProgress);
break;
default:
mDownLoadDialog.dismiss();
installAPK();
break;
}
}
};
public String getVersion_code() {
return Version_code;
}
public void setVersion_code(String version_code) {
Version_code = version_code;
}
public String getVersion_name() {
return version_name;
}
public void setVersion_name(String version_name) {
this.version_name = version_name;
}
public String getVersion_desc() {
return version_desc;
}
public void setVersion_desc(String version_desc) {
this.version_desc = version_desc;
}
public String getVersion_path() {
return version_path;
}
public void setVersion_path(String version_path) {
this.version_path = version_path;
}
private String Version_code="";
private String version_name="";
private String version_desc="";
private String version_path="";
private Context mainContext;
private Handler mGetVersionHandler=new Handler()
{
public void handleMessage(Message msg)
{
JSONObject obj=(JSONObject) msg.obj;
System.out.println(obj.toString());
try {
Version_code=obj.getString("version_code");
version_name=obj.getString("version_name");
version_desc=obj.getString("version_desc");
version_path=obj.getString("version_path");
if(isUpdate())
{
Toast.makeText(mainContext, "hi,有新版本", Toast.LENGTH_SHORT).show();
showNoticeDialog();
}
else
{
Toast.makeText(mainContext, "hi,已经是最新的咯", Toast.LENGTH_SHORT).show();;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public UpdateManager(Context mainContext)
{
this.mainContext=mainContext;
}
public void checkUpdate()
{
RequestQueue requestQueue=Volley.newRequestQueue(mainContext);
JsonObjectRequest json=new JsonObjectRequest(PATH,null,new Listener<JSONObject>(){
@Override
public void onResponse(JSONObject obj) {
// TODO Auto-generated method stub
Message msg=Message.obtain();
msg.obj=obj;
mGetVersionHandler.sendMessage(msg);
}
},new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
// TODO Auto-generated method stub
}
});
requestQueue.add(json);
}
protected boolean isUpdate()//是否需要更新
{
int serverVersion=Integer.parseInt(Version_code);
try {
int localVersion=mainContext.getPackageManager().getPackageInfo("com.example.autoupdate_android",0).versionCode;
String oo=mainContext.getPackageName();
if(serverVersion>localVersion)
{
return true;
}
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
protected void showNoticeDialog()//呈现更新提示框
{
AlertDialog.Builder builder=new AlertDialog.Builder(mainContext);
builder.setTitle("提示");
String message="程序员GG又开发了新版本哟\n"+version_desc;
builder.setMessage(message);
builder.setPositiveButton("更新",new OnClickListener(){//给对话框添加"Yes"按钮
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
showDownloadDialog();
}
});
builder.setNegativeButton("忽略",new OnClickListener(){//对话框添加"No"按钮
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
builder.create().show();
}
protected void showDownloadDialog()//显示下载对话框
{
AlertDialog.Builder builder=new AlertDialog.Builder(mainContext);
builder.setTitle("下载中");
View view1=LayoutInflater.from(mainContext).inflate(R.layout.dialog_progress,null);
process1=(ProgressBar) view1.findViewById(R.id.progress1);
builder.setView(view1);
builder.setNegativeButton("取消",new OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
IsCancelDownLoad=true;
}
});
mDownLoadDialog=builder.create();
mDownLoadDialog.show();
downloadAPK();
//下载begin
}
private void downloadAPK()//开线程下载apk
{
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
String sdpath=Environment.getExternalStorageDirectory()+"/";
mSavePath=sdpath+"ztx";
File dir=new File(mSavePath);
if(!dir.exists())
{
dir.mkdir();
}
try {
HttpURLConnection conn=(HttpURLConnection) new URL(version_path).openConnection();
conn.connect();
InputStream stream=conn.getInputStream();
int totalLength=conn.getContentLength();//文件长度
File apkfile=new File(mSavePath,version_name);
FileOutputStream fos=new FileOutputStream(apkfile);
int count=0;
byte[]buffer=new byte[1024];
while(!IsCancelDownLoad)
{
int read=stream.read(buffer);//本次读取字节数
count+=read;
//进度条的位置等于当前总量/总文件大小
CurrentProgress=(int) ((float)count/totalLength*100);
//todo 进度条 handler
mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_ING);//发送正在下载
if(read<=0)//下载完成 handler
{
mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_OK);//下载完成
break;
}
fos.write(buffer,0,read);//写入文件
}
fos.close();
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
private void installAPK()//安装apk
{
File apkFile=new File(mSavePath,version_name);
if(!apkFile.exists())
{
return;
}
Intent obj=new Intent(Intent.ACTION_VIEW);
obj.setDataAndType(Uri.parse("file://"+apkFile.toString()), "application/vnd.android.package-archive");
mainContext.startActivity(obj);
}
}