您的位置:首页 > 其它

Andorid 版本与服务器版本对比,实现更新

2013-07-18 17:52 239 查看
相信所有的andorid程序,都应该有这个功能,下面我给大家贴个例子出来: 贴一些关键的吧。

一、首先获得自己的版本号和服务器的版本号进行对比

二、提示是否要更新

三、进行apk下载

四、获得权限 进行安装

package com.wtr.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.wrd.R;
import com.wtr.param.SysParam;
import com.wtr.util.HttpUtil;

/**
*
* 注释: 设置功能(修改密码,关于我们,版本更新,提醒设置)
*
* @author yujian 2013-5-2 下午9:18:00
*/
@SuppressWarnings("deprecation")
public class SetupActivity extends Activity {
private RelativeLayout bbgx;// 版本更新
public boolean netConnection;
public static Dialog load;
HttpResponse response;
private static Context m_context = null;
Context context;
private static ProgressDialog m_Dialog = null;
String oldVersion; // 当前应用版本号
JSONObject jsonObject;
private static String path = null;
private static String downUrl;
private static String downName;
private static String remark;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
bbgx = (RelativeLayout) findViewById(R.id.rl_bbgx);
PackageInfo info = null;
try {
info = this.getPackageManager().getPackageInfo(
this.getPackageName(), 0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// 获取当前版本号

oldVersion = info.versionName; // 旧版本
path = getFilesDir() + "/";

// 版本更新
bbgx.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

CheckAppEdtion();
}
});
}

/**
*
* @注释: 检查软件是否是最新版本
* @author Bixingfang 2013-1-22 下午3:03:14 void
*/
private void CheckAppEdtion() {

HttpUtil HttpUtil = new HttpUtil(getApplicationContext());
netConnection = HttpUtil.isNetworkAvailable(SetupActivity.this);// 判断网络是否可用

if (netConnection) {

load = ProgressDialog.show(SetupActivity.this, "正在提交", "请等待");

new Thread() {
@Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(SysParam.versionUpdate); // 你的URL
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //数据						httppost.setEntity(new UrlEncodedFormEntity(
nameValuePairs, HTTP.UTF_8)); // 发送信息
response = httpclient.execute(httppost); // 返回结果
if (response.getEntity() == null
|| "".equals(response.getEntity())) {
handler.sendEmptyMessage(3);
return;
}
String jsonstr = EntityUtils.toString(response
.getEntity());// 转换结果字符串
if (!"null".equals(jsonstr) && jsonstr != null
&& !"".equals(jsonstr)) {
jsonObject = new JSONObject(jsonstr);
downUrl = jsonObject.getString("url"); // 获得apk的下载地址
remark = jsonObject.getString("remark"); // 获得更新内容
handler.sendEmptyMessage(0);

}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
handler.sendEmptyMessage(3);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
handler.sendEmptyMessage(3);
} catch (ParseException e) {
// TODO Auto-generated catch block
handler.sendEmptyMessage(3);
} catch (IOException e) {
// TODO Auto-generated catch block
handler.sendEmptyMessage(3);
} catch (JSONException e) {
// TODO Auto-generated catch block
handler.sendEmptyMessage(3);
} catch (ClassCastException e) {
handler.sendEmptyMessage(3);
}

}

}.start();

} else {
Toast.makeText(getApplicationContext(), "网络不通", 0).show();
}

};

/**
*
* @describe: 执行更新
* @author yujian 2013-5-28 下午4:58:22 void
* @param context
*/
public static void CreateRegisterAlert(Context context) {
m_context = context;
Dialog dialog = new AlertDialog.Builder(context)
.setTitle("系统更新")
.setMessage("已有新版本,是否更新?" + remark)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
m_Dialog = ProgressDialog.show(m_context, "请等待...",
"正在更新,请稍后...", true);
new Thread() {
public void run() {
downLoad();
}
}.start();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

}
}).create();
dialog.show();
};

/**
* 开始下载应用程序
*/
public static void downLoad() {
downName = downUrl.substring(downUrl.lastIndexOf("/") + 1);
Log.i("输出url地址----------------------------", downName);
try {
String web_url = downUrl;
URL url;
HttpURLConnection conn;
url = new URL(web_url);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
FileOutputStream fileOutputStream = null;
if (is != null) {
File file = new File(path, downName);
fileOutputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int ch = -1;
while ((ch = is.read(buf)) != -1) {
fileOutputStream.write(buf, 0, ch);
}
}
fileOutputStream.flush();
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (Exception ex) {

Log.i("aaa", ">>>>>>>>>>>>>");
} finally {
m_Dialog.cancel();
}
install();
};

/**
*
* @注释: 改变文件的权限,进行安装
* @author Bixingfang 2013-1-22 下午3:03:58 void
*/
private static void install() {
Intent intent = new Intent(Intent.ACTION_VIEW);
Log.i("输出path", ">>>>>>>>>>" + path);
FileOutputStream fos;
runCommand("chmod 777 " + path + downName);
Log.i("输出chmod", ">>>>>>>>>>" + "chmod 777 " + path + downName);
intent.setDataAndType(Uri.fromFile(new File(path + downName)),
"application/vnd.android.package-archive");

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
m_context.startActivity(intent);
}

private static boolean runCommand(String command) {

Process process = null;
try {
process = Runtime.getRuntime().exec(command);
Log.i("command", "The Command is : " + command);
process.waitFor();
} catch (Exception e) {
Log.w("Exception ", "Unexpected error - " + e.getMessage());
return false;
} finally {
try {
process.destroy();
} catch (Exception e) {
Log.w("Exception ", "Unexpected error - " + e.getMessage());
}
}
return true;
};

private Handler handler = new Handler() {

@Override
public void handleMessage(Message msg) {
if (load != null)
load.cancel();
switch (msg.what) {
case 0:

try {

double newVersion = Double.valueOf(
jsonObject.getString("version")).doubleValue();// 服务器版本号

Log.i("查看版本信息号", "服务器版本号:" + newVersion + "当前版本号:"
+ oldVersion);

// 获取软件版本号,
if (newVersion > Double.valueOf(oldVersion)) { // 创建更新对话框,并弹出
CreateRegisterAlert(SetupActivity.this);
} else {
Toast.makeText(getApplicationContext(), "已是最新版本", 0)
.show();
}
} catch (Exception e) {

Toast.makeText(getApplicationContext(), "更新失败", 0);
}
break;
case 1:
Toast.makeText(getApplicationContext(), "更新失败", 0).show();
break;
case 2:
Toast.makeText(getApplicationContext(), "已是最新版本", 0).show();
break;
case 3:
Toast.makeText(getApplicationContext(), "联网超时", 0).show();
break;
default:
break;
}
}
};
}

研究代码吧!相信仔细看,绝对能做出来
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐