步骤:
1.检测当前版本的信息AndroidManifest.xml-->manifest-->android:versionName。
2.从服务器获取版本号(版本号存在于xml文件中)并与当前检测到的版本进行匹配,如果不匹配,提示用户进行升级,如果匹配则进入程序主界面。
3.当提示用户进行版本升级时,如果用户点击了确定,系统将自动从服务器上下载并进行自动升级,如果点击取消将进入程序主界面。
获取当前程序的版本号: |
/*
* 获取当前程序的版本号
*/
privateString getVersionName()throwsException{
//获取packagemanager的实例
PackageManager packageManager = getPackageManager();
//getPackageName()是你当前类的包名,0代表是获取版本信息
PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
return packInfo.versionName;
}
从服务器下载apk: |
publicstaticFile getFileFromServer(String path, ProgressDialog pd)throwsException{
//如果相等的话表示当前的sdcard挂载在手机上并且是可用的
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
URL url =newURL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
//获取到文件的大小
pd.setMax(conn.getContentLength());
InputStream is = conn.getInputStream();
File file =newFile(Environment.getExternalStorageDirectory(),"updata.apk");
FileOutputStream fos =newFileOutputStream(file);
BufferedInputStream bis =newBufferedInputStream(is);
byte[] buffer =newbyte[1024];
intlen ;
inttotal=0;
while((len =bis.read(buffer))!=-1){
fos.write(buffer,0, len);
total+= len;
//获取当前下载量
pd.setProgress(total);
}
fos.close();
bis.close();
is.close();
returnfile;
}
else{
returnnull;
}
}
匹配、下载、自动安装:
//安装apk
protected void installApk(File file) {
Intent intent =newIntent();
//执行动作
intent.setAction(Intent.ACTION_VIEW);
//执行的数据类型
intent.setDataAndType(Uri.fromFile(file),"application/vnd.Android.package-archive");//编者按:此处Android应为android,否则造成安装不了
startActivity(intent);
}
二、参考后使用情况:
1.可以下载apk,但安装失败:
1)以为配置文件中需定义了android.permission.INSTALL_PACKAGES,其实不需;
2)以为是要在执行安装的activity中配置
<intent-filter>
<actionandroid:name="android.intent.action.VIEW"/>
<categoryandroid:name="android.intent.category.DEFAULT"/>
</intent-filter>
,其实不是;
3)代码中application/vnd.Android.package-archive有一个字母A大写了,改小写后解决;
原文地址:http://www.open-open.com/lib/view/open1339581191209.html