Android 开发中 app版本更新功能

时间:2021-11-19 21:17:12

每个app中 都不能缺少的一个功能就是app版本的更新功能了。

大概的步骤就是,首先打开app,点开更新或者自动推送,提示有没有新的版本需要更新,如果没有点击取消,如果有则选择下载安装。

代码:

private void showUpdateDialog() {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle("请升级APP至版本" + version);
// builder.setMessage(info.getDescription());
builder.setCancelable(false);

builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
down(); // 在下面的代码段
} else {
Toast.makeText(getActivity(), "SD卡不可用,请插入SD卡",
Toast.LENGTH_SHORT).show();
}
}

});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {

}

});
builder.create().show();
}

private boolean isNeedUpdate() {
// TODO Auto-generated method stub
String v = version;// 服务器上的最新版本的版本号
Log.i("upate", v);
// Toast.makeText(getActivity(), v, Toast.LENGTH_SHORT).show();
if (v.equals(getVersion())) {
Toast.makeText(getActivity(), "以是最新版本!", Toast.LENGTH_SHORT).show();
return false;
} else {
return true;
}
}

// 获取当前本地APP版本的版本号
private String getVersion() {
try {
// 获取packagemanager的实例
PackageManager packageManager = getActivity().getPackageManager();
// getPackageName()是你当前类的包名,0代表是获取版本信息
PackageInfo packageInfo = packageManager.getPackageInfo(
getActivity().getPackageName(), 0);
return packageInfo.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
return "版本号未知";
}
}

// 获取当前本地APP版VersionCode
public static int getVersionCode(Context context)// 获取版本号(内部识别号)
{
try {
PackageInfo pi = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
return pi.versionCode;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}

// 从服务器下载apk
public static File getFileFromServer(String path, Notification notif)
throws Exception {
// 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
// 获取到文件的大小
// pd.setMax(conn.getContentLength());
notif.contentView.setProgressBar(R.id.pb, conn.getContentLength(),
0, false);
InputStream is = conn.getInputStream();
File file = new File(Environment.getExternalStorageDirectory(),
"updata.apk");
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len;
int n = 0;
int total = 0;
while ((len = bis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
total += len;
while (n < 100)
n++;
// 获取当前下载量
// pd.setProgress(total)
notif.contentView.setTextViewText(R.id.down_tv, n + "%");
notif.contentView.setProgressBar(R.id.pb, 100, total, false);
}

fos.close();
bis.close();
is.close();

return file;
} else {
return null;
}
}

@SuppressWarnings({ "static-access", "deprecation" })
void down() {
// final ProgressDialog pd; // 进度条对话框
// pd = new ProgressDialog(getActivity());
// pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// pd.setMessage("正在下载更新");
// pd.show();

manager = (NotificationManager) getActivity().getSystemService(
getActivity().NOTIFICATION_SERVICE);
notif = new Notification(R.drawable.ilex_logo_app, "正在下载",
System.currentTimeMillis());
notif.contentView = new RemoteViews(getActivity().getPackageName(),
R.layout.notification);
notif.contentView.setProgressBar(R.id.pb, 100, 0, false);
final Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
PendingIntent contentIntent = PendingIntent.getActivity(getActivity(),
0, notificationIntent, 0);
notif.contentIntent = contentIntent;
manager.notify(0, notif);

new Thread() {
@Override
public void run() {
File file;
try {
sleep(1000);
file = getFileFromServer(application_iGBS.getApi_downPath(), notif);
manager.notify(0, notif);
// pd.dismiss(); // 结束掉进度条对话框
manager.cancel(0);
update(file);
System.out.println("下载完毕!!!!!!!!!!!");
// 下载完毕后变换通知形式
notif.flags = Notification.FLAG_AUTO_CANCEL;
notif.contentView = null;
Context Context = null;
Intent intent = new Intent(Context, Notification.class);
// 告知已完成
intent.putExtra("completed", "yes");
// 更新参数,注意flags要使用FLAG_UPDATE_CURRENT
PendingIntent contentIntent = PendingIntent.getActivity(
Context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
notif.setLatestEventInfo(Context, "下载完成", "文件已下载完毕",
contentIntent);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}.start();
}

// 安装文件,一般固定写法
void update(File file) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
startActivity(intent);
}
更新app的功能方法有很多,这只是其中的一种,还有就是 要注意和服务器交互要准确。信息什么的要匹配。