Reputation: 603
Is there any possibility to get the versionCode of an App without the getPackageManager? My Problem is, that i want a public Configuration class which have no Activity, so the getPackageManager() does not work. Any Idea?
My current Code:
PackageInfo pinfo;
try {
pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (NameNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
pinfo = null;
}
appVersion = pinfo.versionCode;
Upvotes: 4
Views: 6604
Reputation: 851
Use the following code to get app version code of the current app:
public int getAppVersionCode() {
return BuildConfig.VERSION_CODE;
}
Upvotes: 1
Reputation: 82563
Take an instance of Context in the constructor of your non-activity class and use that to call all such methods.
Something like this:
public class NonActivityClass implements SensorListener{
Context mContext;
public NonActivtiyClass(Context context) {
this.mContext = context;
}
//Rest of your code
}
Then do this to create an object of that class in your Activtiy's onCreate()
:
NonActivityClass nac = new NonActivityClass(this);
Upvotes: 1
Reputation: 83301
You'll have to pass a reference to the Context
(preferably using getApplicationContext()
, to prevent accidental memory leaks) to the public Configuration
class. There is no other way to retrieve the versionCode
of your application. You have to use PackageManager
.
Upvotes: 2