You might ever found custom protocol urls like below:
example://SomeHostPrefix/?UserName=abcdef&SessionId=12345
When you copy this custom protocol url in your mobile browser, you will find that an Android App is activated, rather than a new web page. How to implement such functions in your own Android App? This article offers a walk through example to do so.
Create an Android App in Android Studio, with an empty activity called MainActivity. In order to make the Android App handle the given custom url, in the AndroidManifest.xml, add below code:
Note that we added a new <intent-filter> and a new <data> node in the above code, where you can specify the custom protocol scheme and the host, as highlighted above.
In the Activity’s layout xml, add below UI views:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Custom Protocal Url"
android:textSize="20dp"
android:id="@+id/info_textview"/>
We will use this text view to show the parameters passed from the custom url example://SomeHostPrefix/?UserName=abc&SessionId=123455. Next in the Acivity’s onCreate() function, add below code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri uri = getIntent().getData();
if (uri != null) {
String userName = uri.getQueryParameter(“UserName”);
String sessionId = uri.getQueryParameter(“SessionId”);
TextView infoView = (TextView) findViewById(R.id.info_textview);
infoView.setText(String.format(“%s%s%s%s%s%s%s”,
infoView.getText(), “\n\n“,
“UserName = “, userName, “\n“,
“Session ID = “, sessionId));
}
}
The above code extracts the query parameter in the custom protocol url and dump it into the text view. Build the App and deploy it to the Android Device.
Next create a html file with below single line of text, save it as test_custom_url.html.
<a href=”example://SomeHostPrefix/?UserName=abcdef&SessionId=12345″>Custom Protocol Url</a>
Open this html in your mobile browser, yeah, it will activate your App!
Happy Coding! Visit GitHub to get the project’s source code.
Filed under: Android, Programming Tagged: android, custom protocol, Custom url, example, how to
