0

I am trying to make a program to get the names of all installed applications. In my Activity, I have a method called getApplicationNames that should return this information:

private ArrayList<String> getApplicationNames(Context context){
    ArrayList<String> nameOfRunningApps = new ArrayList<>();
    List<ApplicationInfo> runningApplications = context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);

    for(ApplicationInfo applicationInfo: runningApplications){
        nameOfRunningApps.add(applicationInfo.name);
    }

    return nameOfRunningApps;
}

Now I want to call this method in onCreate():

ArrayList<String> installedProgramNames = getApplicationNames(??);

How do I make an instance of Context in order to call this method? Is this even possible?

Michael Dodd
  • 10,102
  • 12
  • 51
  • 64
Nora
  • 1,825
  • 8
  • 31
  • 47

3 Answers3

1

Activity

Since Activity is basically extending Context in the hierarchy, you can easily achieve your requirement as follows inside onCreate():

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    ArrayList<String> installedProgramNames = getApplicationNames(this);
    ...
}
Sagar
  • 23,903
  • 4
  • 62
  • 62
1

In Android the Activity class extends Context (see the heirarchy diagram at the top of the documentation page), so you can pass a self-reference to your activity into getApplicationNames via the this keyword, i.e.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ArrayList<String> installedProgramNames = getApplicationNames(this);
}

This is also true for other variations of Activity such as AppCompatActivity from the support libraries.

Michael Dodd
  • 10,102
  • 12
  • 51
  • 64
0

Using the application context will do the job.

ArrayList<String> installedProgramNames = getApplicationNames(getApplicationContext());
Sujith Royal
  • 762
  • 10
  • 9