安卓软件版本更新

public class MainActivity extends Activity { private static final String DOWNLO

public class MainActivity extends Activity {
private static final String DOWNLOAD_ADDRESS = "http://10.0.2.2:8080/test1118/weishi360.apk";
private static final String CHECK_ADDRESS = "http://10.0.2.2:8080/test1118/version.xml";
private static final String PACKAGE_NAME = "com.ruicaiedu.day_1224_updatesoftware";

private AlertDialog dialog;
private ProgressBar pb;
private ProgressBar pb_download;
private Apk apk;

private String oldVersion;
private String newVersion;

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:// 有新版本
apk = (Apk) msg.obj;
newVersion = apk.getVersionName();
oldVersion = getVersionName();
if (!newVersion.equals(oldVersion)) {
showDialog();
}
break;

default:
break;
}
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

initWidgets();
parseXmlWithPull(CHECK_ADDRESS);
}

private void initWidgets() {
pb = (ProgressBar) findViewById(R.id.pb);
pb_download=(ProgressBar) findViewById(R.id.pb_download);
}

public String getVersionName() {
String versionName = "";
PackageManager pm = getPackageManager();
try {
PackageInfo packageInfo = pm.getPackageInfo(PACKAGE_NAME,
PackageManager.GET_INSTRUMENTATION);
versionName = packageInfo.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}

public void showDialog() {

dialog = new AlertDialog.Builder(this).setTitle("软件更新提示")
.setMessage("有新版本,现在要更新吗?")
.setPositiveButton("马上更新", new OnClickListener() {

@Override
public void onClick(DialogInterface arg0, int arg1) {
pb.setVisibility(View.GONE);
pb_download.setVisibility(View.VISIBLE);
new DownLoadAsyncTask().execute(DOWNLOAD_ADDRESS);// 让异步任务来下载
}
}).setNegativeButton("残忍拒绝", new OnClickListener() {

@Override
public void onClick(DialogInterface arg0, int arg1) {

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

// 解析xml
public void parseXmlWithPull(String address) {
HttpUtil.sendRequest(address, new HttpCallBackListener() {

@Override
public void onFinish(InputStream is) {
try {
XmlPullParserFactory parserFactory = XmlPullParserFactory
.newInstance();
XmlPullParser pullParser = parserFactory.newPullParser();
pullParser.setInput(is, "utf-8");
int eventType = pullParser.getEventType();
apk = new Apk();

while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
String tagName = pullParser.getName();
if (tagName.equals("name")) {
apk.setName(pullParser.nextText());
} else if (tagName.equals("url")) {
apk.setAddress(pullParser.nextText());
} else if (tagName.equals("version")) {
apk.setVersionName(pullParser.nextText());
}
}
eventType = pullParser.next();
}
Message msg = Message.obtain();
msg.what = 1;
msg.obj = apk;
handler.sendMessage(msg);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

@Override
public void onError(Exception e) {

}
});
}

// 自定义一个异步任务来下载
class DownLoadAsyncTask extends AsyncTask<String, Integer, String> {
int currentSize = 0;
int totalSize = 0;
File file = null;

// 耗时操作
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection = (HttpURLConnection) url.openConnection();

connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
InputStream is = connection.getInputStream();

totalSize = connection.getContentLength();
file = new File(Environment.getExternalStorageDirectory(),
"/360weishi.apk");
DataOutputStream os = new DataOutputStream(
new FileOutputStream(file));
int len = 0;
byte[] buffer = new byte[4096];
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
publishProgress(len);
}
// 其中file就是下载的文件对象
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");// 设置意图的动作
intent.addCategory("android.intent.category.DEFAULT");// 为意图添加额外的数据
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");// 设置意图的数据与类型
startActivity(intent);// 激活该意图

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "下载完成";
}

// 界面更新
@Override
protected void onProgressUpdate(Integer... values) {
currentSize += values[0];
pb.setProgress((int) ((double) currentSize / totalSize * pb
.getMax()));
super.onProgressUpdate(values);
}

// 任务完成
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT)
.show();
pb.setVisibility(View.GONE);
}

}

}