直接贴代码:
config类:
package com.tutor.config;
import org.json.JSONArray;
import org.json.JSONObject;
import com.tutor.update.R;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;
public class Config
{
public String UPDATE_SERVER = "http://10.81.48.181:8080/update/";
public String UPDATE_APKNAME = "";
public String UPDATE_SAVENAME = "update.apk";
public String UPDATE_VERJSON = "ver.json";
public static int newVerCode;
public static String newVerName;
/**
* 获取当前版本号
*
* @param context
* @return
*/
public int getVerCode(Context context)
{
int verCode = -1;
try
{
// 获取packagemanager的实例
PackageManager packageManager = context.getPackageManager();
// getPackageName()是你当前类的包名,0代表是获取版本信息
PackageInfo packInfo =
packageManager.getPackageInfo(context.getPackageName(), 0);
verCode = packInfo.versionCode;
// verCode =
// context.getPackageManager().getPackageInfo(
// "com.example.update", 0).versionCode;
System.out.println("nowcode---?>>>" + verCode);
}
catch (NameNotFoundException e)
{
Log.e("RG", e.getMessage());
}
return verCode;
}
/**
* 获取版本名称
*
* @param context
* @return
*/
public String getVerName(Context context)
{
String verName = "";
try
{
// 获取packagemanager的实例
PackageManager packageManager = context.getPackageManager();
// getPackageName()是你当前类的包名,0代表是获取版本信息
PackageInfo packInfo =
packageManager.getPackageInfo(context.getPackageName(), 0);
verName = packInfo.versionName;
// verName =
// context.getPackageManager().getPackageInfo(
// "com.example.update", 0).versionName;
}
catch (NameNotFoundException e)
{
Log.e("RG", e.getMessage());
}
return verName;
}
// public static String getVerName(Context context)
// {
// String verName =
// context.getResources().getText(R.string.app_versionName)
// .toString();
// return verName;
// }
public static String getAppName(Context context)
{
String verName =
context.getResources().getText(R.string.app_name).toString();
return verName;
}
/**
* 检查服务器的版本
*
* @return
*/
public boolean getServerVerCode()
{
try
{
String verjson =
NetworkTool.getContent(UPDATE_SERVER + UPDATE_VERJSON);
System.out.println("verjson--->>>" + verjson);
JSONArray array = new JSONArray(verjson);
if (array.length() > 0)
{
JSONObject obj = array.getJSONObject(0);
try
{
newVerCode = Integer.parseInt(obj.getString("verCode"));
newVerName = obj.getString("verName");
System.out.println("newVerCode--->>>" + newVerCode);
System.out.println("newVerName--->>>" + newVerName);
}
catch (Exception e)
{
newVerCode = -1;
newVerName = "";
return false;
}
}
}
catch (Exception e)
{
Log.e("RG", e.getMessage());
return false;
}
return true;
}
}
NetworkTool类:
package com.tutor.config;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetworkTool
{
public static String getContent(String filename)
{
URL url;
String str;
try
{
url = new URL(filename);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
int len = conn.getContentLength();
InputStream is = conn.getInputStream();
byte[] by = new byte[len];
is.read(by);
str = new String(by, "UTF-8");
return str;
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
}
UpdateApplication类:
package com.tutor.config;
import android.content.Context;
public class UpdateApplication
{
/**
* 检查更新状态
*
* @param context
* @return
*/
public static boolean getUpdateInfo(Context context)
{
Config cof = new Config();
cof.getServerVerCode();
if (cof.getVerCode(context) < Config.newVerCode)
{
return true;
}
else
{
return false;
}
}
/**
* 马上更新
*
* @param context
*/
public static void newUpdate(Context context)
{
UpdateManager mUpdateManager = new UpdateManager(context);
mUpdateManager.checkUpdateInfo();
}
}
UpdateManager类:
package com.tutor.config;
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 com.tutor.update.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
public class UpdateManager
{
private Context mContext;
// 提示语
private String updateMsg = "有最新的软件包哦,亲快下载吧~";
// 返回的安装包url
private String apkUrl = "http://10.81.48.181:8080/update/UpdateDemo.apk";
private Dialog noticeDialog;
private Dialog downloadDialog;
/* 下载包安装路径 */
private static final String savePath = "/sdcard/updatedemo/";
private static final String saveFileName = savePath
+ "UpdateDemoRelease.apk";
/* 进度条与通知ui刷新的handler和msg常量 */
private ProgressBar mProgress;
private static final int DOWN_UPDATE = 1;
private static final int DOWN_OVER = 2;
private int progress;
private Thread downLoadThread;
private boolean interceptFlag = false;
private Handler mHandler = new Handler()
{
public void handleMessage(Message msg)
{
switch (msg.what)
{
case DOWN_UPDATE:
mProgress.setProgress(progress);
break;
case DOWN_OVER:
installApk();
break;
default:
break;
}
};
};
public UpdateManager(Context context)
{
this.mContext = context;
}
// 外部接口让主Activity调用
public void checkUpdateInfo()
{
showNoticeDialog();
}
private void showNoticeDialog()
{
AlertDialog.Builder builder = new Builder(mContext);
builder.setTitle("软件版本更新");
builder.setMessage(updateMsg);
builder.setPositiveButton("下载", new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
showDownloadDialog();
}
});
builder.setNegativeButton("以后再说", new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
noticeDialog = builder.create();
noticeDialog.show();
}
private void showDownloadDialog()
{
AlertDialog.Builder builder = new Builder(mContext);
builder.setTitle("软件版本更新");
final LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.progress);
builder.setView(v);
builder.setNegativeButton("取消", new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
interceptFlag = true;
}
});
downloadDialog = builder.create();
downloadDialog.show();
downloadApk();
}
private Runnable mdownApkRunnable = new Runnable()
{
@Override
public void run()
{
try
{
URL url = new URL(apkUrl);
HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
File file = new File(savePath);
if (!file.exists())
{
file.mkdir();
}
String apkFile = saveFileName;
File ApkFile = new File(apkFile);
FileOutputStream fos = new FileOutputStream(ApkFile);
int count = 0;
byte buf[] = new byte[24];
do
{
int numread = is.read(buf);
count += numread;
progress = (int) (((float) count / length) * 100);
// 更新进度
mHandler.sendEmptyMessage(DOWN_UPDATE);
if (numread <= 0)
{
// 下载完成通知安装
mHandler.sendEmptyMessage(DOWN_OVER);
break;
}
fos.write(buf, 0, numread);
} while (!interceptFlag);// 点击取消就停止下载.
fos.close();
is.close();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
};
/**
* 下载apk
*
* @param url
*/
private void downloadApk()
{
downLoadThread = new Thread(mdownApkRunnable);
downLoadThread.start();
}
/**
* 安装apk
*
* @param url
*/
private void installApk()
{
if (downloadDialog.isShowing())
{
downloadDialog.dismiss();
}
File apkfile = new File(saveFileName);
if (!apkfile.exists())
{
return;
}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
"application/vnd.android.package-archive");
mContext.startActivity(i);
}
}
MainAcitivity:
package com.tutor.update;
import com.tutor.config.UpdateApplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainAcitivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bt = (Button) findViewById(R.id.button1);
bt.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if (UpdateApplication.getUpdateInfo(MainAcitivity.this))
{
UpdateApplication.newUpdate(MainAcitivity.this);
}
else
{
Toast.makeText(MainAcitivity.this, "程序已经是最新状态!谢谢使用",
Toast.LENGTH_SHORT).show();
}
}
});
}
}