package com.example.android_apk_install; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; /** * 版本信息 * @author Administrator * */ public class PackageUtils { private Context context; private PackageManager manager; private PackageInfo info; public PackageUtils(Context context) { this.context = context; init(); } /** * 初始化数据 */ public void init() { manager = context.getPackageManager(); try { info = manager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } public int getVersionCode() { return info.versionCode; } /** * * @return */ public String getVersionName() { return info.versionName; } /** * 是否需要升级 * @param oldVersion * @param newVersion * @return */ public boolean isUpgrada(int oldVersion,int newVersion) { boolean flag = false; flag = newVersion > oldVersion ? true : false; return flag; } }
测试
package com.example.android_apk_install; import android.os.Bundle; import android.app.Activity; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.view.Menu; import android.widget.Toast; public class MainActivity extends Activity { PackageUtils utils; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); utils=new PackageUtils(this); int currVersionCode=utils.getVersionCode(); boolean flag=utils.isUpgrada(currVersionCode, 2); if (flag) { Toast.makeText(this, "有新版本", 1).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }