Using Android Intents Tutorial
A Little Manifest Destiny
I’ve re-written the createAdapter method in our main activity to automatically populate the list with the other activities.
First I create an Intent using the action we specified. Next I add a category to the Intent. So at this point the intent will only use activities which have both that action and that category in their intent-filter.
Next I get an instance of PackageManager. We use this to call queryIntentActivities. This handy method will return a list of all of the activities that could be activated by the intent you pass in as a parameter. Now that we have this list, we loop through the list and get the label for each activity. I went ahead and put in some logic to get the activity name if the label isn’t present, since the label is optional. Finally, we save the results to a string array and viola! We have a dynamic list.
You might have noticed that this list is shorter than the previous one. That’s because we have one more activity to create. Let’s go ahead and create a class named FinalActivity and put an entry into the Android Manifest for it.
Now when you run you should see the same menu as before.
Finally, we need to rewrite our onListItemClick method to also be dynamic. I am just going to use the same method used to list our activities.
Instead of looping through all of the activities, we just use the position integer to get the selected activity. We create an empty Intent, and then use the setClassName that accepts String values to identify the class. We are just going to call all of the activities using startActivityForResult. Since we are checking for the result code RESULT_OK an activity that isn’t setup to return anything should just fail this if statement and skip our popup code.
This should be enough to get your started with a foundation for working with Intents. If you want, you can download the source code for this entire project here.
As always, please leave comments with any questions you have on the subject, or anything you would like to see elaborated on in a future article. Thank you for reading.
No comments:
Post a Comment