本篇文章转载之http://blog.csdn.net/harvic880925/article/details/25191159
首先要在AndroidManifest.xml加入权限
<uses-permission android:name="android.permission.INTERNET"/>
<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
新建一个common类:
package com.test.common;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;
public class Common {
public static final String SERVER_IP="http://192.168.1.1/";
public static final String SERVER_ADDRESS=SERVER_IP+"links/DownLoadApk/index.php";//软件更新包地址
public static final String UPDATESOFTADDRESS=SERVER_IP+"links/DownLoadApk/test.apk";//软件更新包地址
/**
* 向服务器发送查询请求,返回查到的StringBuilder类型数据
*
* @param ArrayList
* <NameValuePair> vps POST进来的参值对
* @return StringBuilder builder 返回查到的结果
* @throws Exception
*/
public static StringBuilder post_to_server(List<NameValuePair> vps) {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpResponse response = null;
// 创建httpost.访问服务器网址
HttpPost httpost = new HttpPost(SERVER_ADDRESS);
StringBuilder builder = new StringBuilder();
httpost.setEntity(new UrlEncodedFormEntity(vps, HTTP.UTF_8));
response = httpclient.execute(httpost); // 执行
if (response.getEntity() != null) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String s = reader.readLine();
for (; s != null; s = reader.readLine()) {
builder.append(s);
}
}
return builder;
} catch (Exception e) {
// TODO: handle exception
Log.e("msg",e.getMessage());
return null;
} finally {
try {
httpclient.getConnectionManager().shutdown();// 关闭连接
// 这两种释放连接的方法都可以
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("msg",e.getMessage());
}
}
}
/**
* 获取软件版本号
* @param context
* @return
*/
public static int getVerCode(Context context) {
int verCode = -1;
try {
verCode = context.getPackageManager().getPackageInfo(
"com.test.tt", 0).versionCode;
} catch (NameNotFoundException e) {
Log.e("msg",e.getMessage());
}
return verCode;
}
/**
* 获取版本名称
* @param context
* @return
*/
public static String getVerName(Context context) {
String CurrverName = "";
try {
CurrverName = context.getPackageManager().getPackageInfo(
"com.test.tt", 0).versionName;
} catch (NameNotFoundException e) {
Log.e("msg",e.getMessage());
}
return CurrverName;
}
}
在主activity中加入
//检查版本更新测试
class checkNewestVersionAsyncTask extends AsyncTask<Void, Void, Boolean>
{
@Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
if(GetVersionFromServer())
{
String m_CurrVersion = Common.getVerName(getApplicationContext());
if (!m_LatestVersion.equals(m_CurrVersion)) {
return true;
} else {
return false;
}
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
if (result) {//如果有最新版本
NewVersionUpdate(); // 更新新版本
}else {
LatestVersion(); // 提示当前为最新版本
}
super.onPostExecute(result);
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
}
private void InitVersion(){
m_progressDlg = new ProgressDialog(this);
m_progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
m_progressDlg.setIndeterminate(false);
m_appNameStr = "DownLoad.apk";
}
public static void CheckVersion(String ver){ //程序获取版本号
try {
Message message = handler.obtainMessage();
message.what = 100;
message.obj = ver;
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
//服务器获取最新版本号
public Boolean GetVersionFromServer(){
StringBuilder builder = new StringBuilder();
JSONArray jsonArray = null;
try {
// 构造POST方法的{name:value} 参数对
List<NameValuePair> vps = new ArrayList<NameValuePair>();
// 将参数传入post方法中
vps.add(new BasicNameValuePair("action", "checkNewestVersion"));
builder = Common.post_to_server(vps);
jsonArray = new JSONArray(builder.toString());
if (jsonArray.length()>0) {
if (jsonArray.getJSONObject(0).getInt("id") == 1) {
m_LatestVersion = jsonArray.getJSONObject(0).getString("verName");
return true;
}
}
return false;
} catch (Exception e) {
Log.e("msg",e.getMessage());
return false;
}
}
private void NewVersionUpdate(){
String VersionName = Common.getVerName(getApplicationContext());
String str = "当前版本"+VersionName+",发现新版本" + m_LatestVersion + ",是否更新?";
Dialog dialog = new AlertDialog.Builder(this).setTitle("版本更新").setMessage(str)
// 设置内容
.setPositiveButton("更新",// 设置确定按钮
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
m_progressDlg.setTitle("正在玩命下载");
m_progressDlg.setMessage("请稍候...");
DownLoadApk(Common.UPDATESOFTADDRESS); //开始下载
}
})
.setNegativeButton("暂不更新",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
//finish();
//System.exit(0);
}
}).create();// 创建
// 显示对话框
dialog.setCanceledOnTouchOutside(false);//设置对话框外触摸无效,这样有大bug的时候,强制更新
dialog.show();
}
private void LatestVersion(){
String VersionName = Common.getVerName(getApplicationContext());
String str = "当前版本"+VersionName+",为最新版本,无需更新";
Dialog dialog = new AlertDialog.Builder(this).setTitle("软件更新")
.setMessage(str)// 设置内容
.setPositiveButton("确定",// 设置确定按钮
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).create();// 创建
// 显示对话框
dialog.setCanceledOnTouchOutside(false);//设置对话框外触摸无效
dialog.show();
}
private void DownLoadApk(final String url){
m_progressDlg.show();
new Thread(){
public void run(){
HttpClient client = new DefaultHttpClient();
HttpGet geturl = new HttpGet(url);
HttpResponse response;
try {
response = client.execute(geturl);
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
m_progressDlg.setMax((int)length);//设置进度条的最大值
InputStream is = entity.getContent();
FileOutputStream fileOutputStream = null;
if (is != null) {
File file = new File(
Environment.getExternalStorageDirectory(),
m_appNameStr);
fileOutputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int ch = -1;
int count = 0;
while ((ch = is.read(buf)) != -1) {
fileOutputStream.write(buf, 0, ch);
count += ch;
if (length > 0) {
m_progressDlg.setProgress(count);
}
}
}
fileOutputStream.flush();
if (fileOutputStream != null) {
fileOutputStream.close();
}
down(); //告诉HANDER已经下载完成了,可以安装了
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
private void down() {
handler.post(new Runnable() {
public void run() {
m_progressDlg.cancel();
update();
}
});
}
void update() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), m_appNameStr)),
"application/vnd.android.package-archive");
startActivity(intent);
}