How to get the build/version number of your Android application?

前端 未结 30 2398
刺人心
刺人心 2020-11-22 11:00

I need to figure out how to get or make a build number for my Android application. I need the build number to display in the UI.

Do I have to do something with

30条回答
  •  忘掉有多难
    2020-11-22 11:27

    As I had to get only version code and check whether app is updated or not, if yes, I had to launch the playstore to get updated one. I did this way.

    public class CheckForUpdate {
    
    public static final String ACTION_APP_VERSION_CHECK="app-version-check";
    
    public static void launchPlayStoreApp(Context context)
    {
    
        final String appPackageName = context.getPackageName(); // getPackageName() from Context or Activity object
        try {
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
        } catch (android.content.ActivityNotFoundException anfe) {
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
        }
    
    }
    
    public static int getRemoteVersionNumber(Context context)
    {
        int versionCode=0;
        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            String version = pInfo.versionName;
            versionCode=pInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }
    
    }
    

    Then I saved version code using shared preference by creating an util class.

    public class PreferenceUtils {
    
    // this is for version code
    private  final String APP_VERSION_CODE = "APP_VERSION_CODE";
    private  SharedPreferences sharedPreferencesAppVersionCode;
    private SharedPreferences.Editor editorAppVersionCode;
    private static Context mContext;
    
    public PreferenceUtils(Context context)
    {
        this.mContext=context;
        // this is for app versioncode
        sharedPreferencesAppVersionCode=mContext.getSharedPreferences(APP_VERSION_CODE,MODE_PRIVATE);
        editorAppVersionCode=sharedPreferencesAppVersionCode.edit();
    }
    
    public void createAppVersionCode(int versionCode) {
    
        editorAppVersionCode.putInt(APP_VERSION_CODE, versionCode);
        editorAppVersionCode.apply();
    }
    
    public int getAppVersionCode()
    {
        return sharedPreferencesAppVersionCode.getInt(APP_VERSION_CODE,0); // as default  version code is 0
         }
       }
    

提交回复
热议问题