How to open a website or an app in Google Play, from preferences

It is quite easy to have a preference item in your app to link to your website, or an app in Google Play.

This does not even require any additional permissions for your app.

However, it would be great to make sure the user knows what happens if the presses the preference item, for example if it will open a new page in the browser.

To have a preference item open a website:

Just add an intent inside your preference item, and it will open the url in the web browser when it is touched.

<Preference  
 android:title="Visit the website"
 android:key="info">

   <intent
   android:action="android.intent.action.VIEW"
   android:data="http://www.envyandroid.com"
   />

</Preference>  

To have a preference item open the Google Play app at a specific app:

For example if you want to link to your other apps.

<Preference  
 android:title="Go to app in Google Play"
 android:key="info">

   <intent
   android:action="android.intent.action.VIEW"
   android:data="market://details?id=com.envyandroid.tempsens"
   />

</Preference>  

You can also link to other things in the Google Play app, such as the “top free” app list.

How to perform some other task when the user clicks the preference item

Given the preference item in the first example, you could specify the open website action in code instead of xml.

You could ofcourse also apply any other action, when the user clicks the preference item. To do it in code, you would write:

Preference preference = (Preference) findPreference("info");

preference.setOnPreferenceClickListener(new OnPreferenceClickListener() {

    public boolean onPreferenceClick(Preference preference) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.envyandroid.com"));
        startActivity(intent);
    }
});

The important thing here, is to get hold of the preference item, before adding a click listener to it.

You use the key attribute specified in the xml file, at line 3, to get hold of the right preference item.

comments powered by Disqus