4

I'm trying to figure out how i can implement this code into my existing source code. Currently i have some source that displays a list-view of all the installed apps and on-click will send intent to the application. I'm needing some support on how to pull the icon and add this into the list view.

Any help, source code editing, links, etc would help me resolve this.

Thank you

ListInstalledActivitiesActivity

public class ListInstalledActivitiesActivity extends ListActivity {

    // Buffer used to store package and class information, and also determine the number of installed activities
    private ArrayList<String[]> _activitiesBuffer = null;

    // Buffers for package and class information
    private String[] _packages = null;
    private String[] _classes = null;

    // Index used to fill buffers
    private int _index = 0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main3);
        // Get all installed activities (package and class information for every activity)
        getAllInstalledActivities();              

        // Set content to GUI
        setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, _classes));

        ListView lv = getListView();
        lv.setTextFilterEnabled(true);

        // Add listener
        lv.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                // When clicked, show a toast with the selected activity
                Toast.makeText(
                    getApplicationContext(), 
                    ((TextView) view).getText(), 
                    Toast.LENGTH_SHORT).show();

                // When clicked, start selected activity, if allowed or possible
                try {

                    Intent intent = new Intent().setClassName(
                            _packages[position], // package 
                            _classes[position]); // class
                    startActivity(intent);

                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Unable to start selected application.", Toast.LENGTH_SHORT);
                }

          } // public void onItemClick(AdapterView<?> parent, View view, int position, long id)

        });

    } // public void onCreate(Bundle savedInstanceState)

    /*
     * Get all installed activities
     */
    private void getAllInstalledActivities() {


        // Initialize activities buffer
        _activitiesBuffer = new ArrayList<String[]>();

        final Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        final List<ResolveInfo> pkgAppsList = getPackageManager().queryIntentActivities( intent, 0);

        Iterator<ResolveInfo> iterator1 = pkgAppsList.iterator();
        while (iterator1.hasNext()) {

            ResolveInfo resolveInfo = iterator1.next();

            String[] buf = new String[] {
                    resolveInfo.activityInfo.packageName, 
                    resolveInfo.activityInfo.name};

            _activitiesBuffer.add(buf);

        } // while (iterator1.hasNext())

        _packages = new String[_activitiesBuffer.size()];
        _classes = new String[_activitiesBuffer.size()];

        Iterator<String[]> iterator2 = _activitiesBuffer.iterator();
        while (iterator2.hasNext()) {

            String[] buf = iterator2.next();

            // Store package information
            _packages[_index] = buf[0]; 

            // Store class information
            _classes[_index] = buf[1];

            _index++;

        } // while (iterator2.hasNext())

    } // private void getAllInstalledActivities()

      }

main3.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical" >

     <ListView
         android:id="@+id/android:list"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent" />

      <!-- <ImageView -->
      <!--android:id="@+id/ImageView02" -->
      <!--android:layout_width="fill_parent" -->
      <!--android:layout_height="wrap_content" -->
      <!--android:layout_marginBottom="10dp" -->
      <!--android:paddingBottom="5dp" -->


      </LinearLayout>
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
Jaison Brooks
  • 5,816
  • 7
  • 43
  • 79
  • 1
    you will need to create a custom adapter by extending BaseAdapter for implementing second option see [this](http://shenhengbin.wordpress.com/2012/03/17/listview-simpleadapter/) which help you more for solving current issue – ρяσѕρєя K Dec 28 '12 at 05:42

2 Answers2

3

To fetch the names and icons of the installed applications, you need to use Package Manager class, here is a snippet of code, that will let you fetch application's name and icons

   import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class FetchApplicationsActivity extends Activity {

    TextView data;
    ImageView image1;
    LinearLayout holdlayout;
    View l1;
    private ArrayList results;
    List<ResolveInfo> list;
    TextView result;
    String str = "";
    Drawable icon;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        l1 = findViewById(R.id.Layout1);
        results = new ArrayList();
        PackageManager pm = this.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        list = pm.queryIntentActivities(intent,
                PackageManager.PERMISSION_GRANTED);
        for (ResolveInfo rInfo : list) {
            str = rInfo.activityInfo.applicationInfo.loadLabel(pm).toString()
                    + "\n";
            results.add(rInfo.activityInfo.applicationInfo.loadLabel(pm)
                    .toString());
            Log.w("Installed Applications", rInfo.activityInfo.applicationInfo
                    .loadLabel(pm).toString());
            icon = rInfo.activityInfo.applicationInfo.loadIcon(pm);
            holdlayout = new LinearLayout(getApplicationContext());
            holdlayout.setOrientation(LinearLayout.HORIZONTAL);
            data = new TextView(getApplicationContext());
            data.setText(str);
            image1 = new ImageView(getApplicationContext());
            image1.setBackgroundDrawable(icon);
            ((ViewGroup) holdlayout).addView(image1);
            ((ViewGroup) holdlayout).addView(data);
            ((ViewGroup) l1).addView(holdlayout);

        }
    }
}

Edit- You can define your main.xml as,

?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >



    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >


        <LinearLayout
        android:id="@+id/Layout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >



    </LinearLayout>
    </ScrollView>

</LinearLayout>

Here I have created dynamic textviews, Imageviews and layouts to show the names and icons. You can create your own customized list to show this.

Edit2- Here is a good link on how to create customized list and also look here. I think these will solve the issue.

Community
  • 1
  • 1
Sahil Mahajan Mj
  • 11,033
  • 8
  • 53
  • 100
  • Thank you so much for the source code i really appreciate the response. Now being early into android development, how would i start making my exsisting code updated with this included. I see that you have code a view with the id of Layout1, do i need to change my main3.xml id to Layout1, sorry to ask very simple questions, appreciate the support – Jaison Brooks Dec 28 '12 at 05:57
  • I have edited my answer to show what you could write in main3.xml – Sahil Mahajan Mj Dec 28 '12 at 06:01
  • Im trying to edit my code to make it work, Would you recommend keeping any of my current code. Or should i start over with the code you have supplied – Jaison Brooks Dec 28 '12 at 07:24
  • are you able to edit my current code at all, if so could you plug that code into the current setup, if not ill scap it and start with the code you have provided. Thanks again – Jaison Brooks Dec 28 '12 at 07:25
  • you could create a new project and check if my code works and then get on it. – Sahil Mahajan Mj Dec 28 '12 at 07:26
  • ill create a new project, do im just input your code after i set the content view, as i stated im new to programming android and java so i want to ensure im going to actually be able to make this code work at some point. Thanks again – Jaison Brooks Dec 28 '12 at 07:32
  • It works!!!! Thanks, So it loads the icons and the name of the application, Now what i would like to do is add the same functionality as i had before so that onClick of the item(app) it will intent to that application. like i have in my previous code. Thank You so much for helping me – Jaison Brooks Dec 28 '12 at 07:56
  • i understand the basic concept on listviews and what not, Would any of my existing source code be salvageable to make it the code you have provided basically pull the package name or whatever and send intent to it upon click of the listview item. – Jaison Brooks Dec 28 '12 at 08:14
  • here you will need **Customized list**, it is different from the simple list, then in the **onClick()** event of the list pass the intent, that you have used in your question. hopefully it will work. – Sahil Mahajan Mj Dec 28 '12 at 08:20
  • No problem, do you mind emailing me and i can attempt to built this customized list and you could overlook it for me shoot me a email @ jaisonbrooks@gmail.com – Jaison Brooks Dec 28 '12 at 08:35
  • I have edited my answer. You can have a look at those links. let me know when your issue is solved. – Sahil Mahajan Mj Dec 28 '12 at 08:43
  • ill check the links out and see what i can do and update my source code on this page and comment you back when i've updated it. Thanks again i really appreciate this – Jaison Brooks Dec 28 '12 at 08:53
3

I follow this tutorial and its very helpful to me:

class PInfo {
    private String appname = "";
    private String pname = "";
    private String versionName = "";
    private int versionCode = 0;
    private Drawable icon;
    private void prettyPrint() {
        Log.v(appname + "\t" + pname + "\t" + versionName + "\t" + versionCode);
    }
}

private ArrayList<PInfo> getPackages() {
    ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
    final int max = apps.size();
    for (int i=0; i<max; i++) {
        apps.get(i).prettyPrint();
    }
    return apps;
}

private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) {
    ArrayList<PInfo> res = new ArrayList<PInfo>();        
    List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
    for(int i=0;i<packs.size();i++) {
        PackageInfo p = packs.get(i);
        if ((!getSysPackages) && (p.versionName == null)) {
            continue ;
        }
        PInfo newInfo = new PInfo();
        newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
        newInfo.pname = p.packageName;
        newInfo.versionName = p.versionName;
        newInfo.versionCode = p.versionCode;
        newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
        res.add(newInfo);
    }
    return res; 
}
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437