Monday, March 31, 2014

Android Tip - Intercepting Links on Browsers

Have you ever encountered this situation where you click on a YouTube link on the browser on your Android device and you are prompted to view the video either using the YouTube app or on the browser? How do you make your app respond to a particular type of links on the browser?

You do so, you just need to add in the necessary intent filter to your app’s AndroidManifest.xml file. The following code snippets shows how your app can be launched when the user taps on a link that points to http://learn2develop.net/2014:

        <intent-filter>
            <action android:name=
                "android.intent.action.VIEW" />
            <category android:name=
                "android.intent.category.DEFAULT" />
            <category android:name=
                "android.intent.category.BROWSABLE" />
               
            <data android:scheme="http"
                  android:host="learn2develop.net"
                  android:pathPrefix="/2014" />
        </intent-filter>          

In your activity, you can retrieve the URL that the user has tapped using the getDataString() method of the Intent object:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        Intent i = getIntent();            
        Toast.makeText(this, i.getAction(),
            Toast.LENGTH_LONG).show();       
        Toast.makeText(this, i.getDataString(),
            Toast.LENGTH_LONG).show();           
    }

The following URLs will trigger your app:



But the following URLs won’t:
·       http://www.amazon.com

No comments: