Datenshi Datenshi - 5 months ago 15
Android Question

Opening android deep links from app

I am implementing deep links inside my app and could not find a way, or example about opening them from inside my own app. For example: I wish that opening certain banner would open

myapp://game/1
link which would lead to another activity inside my app. How can I do that ?

Answer

In the manifest you should register the deep linking scheme.

    <activity android:name=".DeepLinkingActivity"
        android:configChanges="orientation|screenSize" >
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.BROWSABLE" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:scheme="myapp" />
        </intent-filter>
    </activity>

With this the DeepLinkingActivity will open when the the link with the defined scheme is clicked. And in the activity handle what to do:

private final String GAME_LINK = "game";
private final String VIDEO_LINK = "video";

private static String PASSED_LINK = "PassedLink";

public static Intent createIntent(String link, Context context) {
    Intent intent = new Intent(context, DeepLinkingActivity.class);
    intent.putExtra(PASSED_LINK, link);
    return intent;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    String host;
    String link = getIntent().getStringExtra(PASSED_LINK);
    if(TextUtils.isEmpty(link)) {
       Intent intent = getIntent();
        if (intent.getData() != null) {
            Uri data = intent.getData();
            host = data.getHost();
        } else {
           // No links
        }
    } else {
          Uri data = Uri.parse(link);
          host = data.getHost();
    }

    if(host.equals(GAME_LINK))  {
        // myapp://game/
        // Do something
    } else if(host.equals(VIDEO_LINK)){
        // myapp://video/
        // Do something
    } else {
        // Do something
    }
 ...
 }

Then you can call from your widget:

widget.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(DeepLinkingActivity.createIntent("linik_for_this_wiget"), getContext());
        }
    });

If you have links in WebView you could also override shouldOverrideUrlLoading

Comments