I need to write some util class by myself and I need the packagename of android app. While I found the packageManager which only can be used in Activity and so on that has c
Use : getPackageManager().getPackageInfo(getPackageName(), 0).packageName
Or just MyContext.getPackageName()
You can also create a function:
public String getPackageName(Context context) {
return context.getPackageName();
}
The following constant is available without the need for a context.
BuildConfig.APPLICATION_ID
I think getPackageName()
is available directly within activity without calling getApplicationContext
. Checked it myself.Working good.
getApplicationContext().getPackageName()
will give the package name.
List<ApplicationInfo> packages;
PackageManager pm;
pm = getPackageManager();
get a list of installed apps.
packages = pm.getInstalledApplications(0);
ActivityManager mActivityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
for (ApplicationInfo packageInfo : packages) {
//packageInfo.packageName contains package name
}
you can create a Util Class this way:
public class AppInfo{
private static Context cxt;
public static String PACKAGE_INFO;
public static String init(Context context){
cxt = context;
PACKAGE_INFO = cxt.getPackageName();
}
}
then you can use it this way
public class MyActivity extends Activity{
@Override
public void onCreate(Bundle bundle){
...
AppInfo.init(getApplicationContext());
...
}
}
then you can call it this way:
public class someClass{
public void someMethod(){
String packageInfo = AppInfo.PACKAGE_INFO;
//Do what you wish
}
}