Nora
Nora

Reputation: 1893

How to call a method contained in an Android activity?

I have an Activity-class with a method called getPacketNames() that returned the names of some installed packages.

private ArrayList<CharSequence> getPackageNames(){
    ArrayList<CharSequence> packageNames = new ArrayList<>();
    List<PackageInfo> packagesInfos = getPackageManager().getInstalledPackages(0);

    for(PackageInfo packageInfo: packagesInfos){
        if(!isSystemApp(packageInfo)){
            packageNames.add(packageInfo.packageName);
        }
    }

    return packageNames;
}

I want to make it easy for someone else to call this method from another class. However, in order to do so, they would have to create an instance of the activity. This seems cumbersome, and not correct.

Is thee any way I can create this method outside of an Activity? When I create a separate class and copy-paste the method it does not work, because getPackageManager().getInstalledPackages(0) seems to need to be in an activity.

Upvotes: 2

Views: 71

Answers (2)

Sam
Sam

Reputation: 31

Sagar's answer is correct and you should follow that. If you are going to create a util class don't forget to add a private constructor, so that your util class will not be instantiated.

For a "hacky" and bad solution, you can always define your method as public static in your activity class and call it from elsewhere with YourActivity.methodname. But this approach will fail especially if you experiment with Don't Keep Activities option.

Upvotes: 1

Sagar
Sagar

Reputation: 24907

You should't attempt to do that. Instead create a UtilityClass and make your getPackageNames() as static method.

public final class MyUtils {

    public static ArrayList<CharSequence> getPackageNames(final Context context){
        ArrayList<CharSequence> packageNames = new ArrayList<>();
        List<PackageInfo> packagesInfos = context.getPackageManager().getInstalledPackages(0);

        for(PackageInfo packageInfo: packagesInfos){
            if(!isSystemApp(packageInfo)){
                packageNames.add(packageInfo.packageName);
            }
        }

        return packageNames;
    }
    private static boolean isSystemApp(...){
        ...
    }
}

Then from the Activity, you can access it as follows:

MyUtils.getPackageNames(this);

Upvotes: 5

Related Questions