2

I am creating an app like play store for my company. I have upload apk on my server from my web application. I have downloaded apk from url in my android app and prompt to install screen. Now what I want that I am getting new version code and package name from API. I want to get version code of installed app from package name. How can I get version code from package name which I get from API ?

Moin Khan
  • 674
  • 2
  • 9
  • 27

3 Answers3

2

All the provided answers are correct. However, be aware that PackageInfo.versionCode has been deprecated in API Level 28. Use getLongVersionCode instead for devices running Android Pie or later as below...

    var info: PackageInfo? = null
    var versionCode: Long? = null

    try {
        info = context?.packageManager?.getPackageInfo(context?.packageName, 0)
        versionCode =
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P)  info?.versionCode?.toLong()
        else info?.longVersionCode 
    }
    catch(e: PackageManager.NameNotFoundException){

    }
Leo
  • 14,625
  • 2
  • 37
  • 55
0

use this

public Long getVersionNo(String packageName){
    PackageInfo packageInfo  = null;
    try {
        packageInfo = getPackageManager().getPackageInfo(packageName, 0);
        return packageInfo.getLongVersionCode();
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
   return null;
}

pass package name to this function and it will return the version number of the app installed on device . If app is not found it will return null .

Manohar
  • 22,116
  • 9
  • 108
  • 144
0
List<PackageInfo> packagesInstalledList = getPackageManager().getInstalledPackages(PackageManager.GET_META_DATA);
PackageInfo packageInfo = context.getPackageManager().getPackageInfo( "com.xyz", 0 );

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P){
    long versionCode = PackageInfoCompat.getLongVersionCode(packageInfo);
}else {
    long versionCode = packageInfo.versionCode;//PackageInfo Deprecated in API-28
}

String versionName = packageInfo.versionName;
Vinay
  • 732
  • 5
  • 8