Git Product home page Git Product logo

deeplinkdispatch's Introduction

DeepLinkDispatch

Build Status

DeepLinkDispatch provides a declarative, annotation-based API to define application deep links.

You can register an Activity to handle specific deep links by annotating it with @DeepLink and a URI. DeepLinkDispatch will parse the URI and dispatch the deep link to the appropriate Activity, along with any parameters specified in the URI.

Example

Here's an example where we register SampleActivity to pull out an ID from a deep link like example://example.com/deepLink/123. We annotated with @DeepLink and specify there will be a parameter that we'll identify with id.

@DeepLink("example://example.com/deepLink/{id}")
public class SampleActivity extends Activity {
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    if (intent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false)) {
      Bundle parameters = intent.getExtras();
      String idString = parameters.getString("id");
      // Do something with idString
    }
  }
}

Multiple Deep Links

Sometimes you'll have an Activity that handles several kinds of deep links:

@DeepLink({"foo://example.com/deepLink/{id}", "foo://example.com/anotherDeepLink"})
public class MainActivity extends Activity {
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    if (intent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false)) {
      Bundle parameters = intent.getExtras();
      String idString = parameters.getString("id");
      // Do something with idString
    }
  }
}

DeepLinkHandler Annotations

You can annotate a Kotlin object that is extending com.airbnb.deeplinkdispatch.handler.DeepLinkHandler with an @DeepLink annotation.

@DeepLink("foo://example.com/handlerDeepLink/{param1}?query1={queryParameter}")
object ProjectDeepLinkHandler : DeepLinkHandler<ProjectDeepLinkHandlerArgs>() {
    override fun handleDeepLink(parameters: ProjectDeepLinkHandlerArgs) {
        /**
         * From here any internal/3rd party navigation framework can be called the provided args.
         */
    }
}

data class ProjectDeepLinkHandlerArgs(
    @DeeplinkParam("param1", DeepLinkParamType.Path) val number: Int,
    @DeeplinkParam("query1", DeepLinkParamType.Query) val flag: Boolean?,
)

DeepLinkDispatch will then call the handleDeepLink function in your handler with the path placeholders and queryParameters converted into an instance of the specified type class.

Query parameter conversion is supported for nullable and non nullable versions of Boolean,Int, Long,Short,Byte,Double,Float and String as well as the same types in Java. For other types see: Type conversion

This will give compile time safety, as all placeholders and query parameters specified in the template inside the @DeepLink annotation must be present in the arguments class for the processor to pass. This is also true the other way around as all fields in the arguments class must be annotated and must be present in the template inside the annotation.

From this function you can now call into any internal or 3rd party navigation system without any Intent being fired at all and with type safety for your arguments.

Note: Even though they must be listed in the template and annotation, argument values annotated with DeepLinkParamType.Query can be null as they are allowed to not be present in the matched url.

Type conversion

If you want to support the automatic conversions of types other than Boolean,Int,Long,Short,Byte, Double,Float and String in deep link argument classes you can add support by adding your own type converters in the DeepLinkDelegate class that you are instantiating.

Type conversion is handled via a lambda that you can set in the DeepLinkDelegate constructor.

All type converters you want to add get added to an instance of TypeConverters which then in turn gets returned by the lambda. This way you can add type converters on the fly while the app is running (e.g. if you just downloaded a dynamic feature which supports additional types).

There is an example of this in the sample app for this. Here is a brief overview:

TypeConverters typeConverters = new TypeConverters();
typeConverters.put(ColorDrawable.class, value -> {
  switch (value.toLowerCase()) {
    case "red":
      return new ColorDrawable(0xff0000ff);
  }
});

Function0<TypeConverters> typeConvertersLambda = () -> typeConverters;

DeepLinkDelegate deepLinkDelegate = new DeepLinkDelegate(
  ...
  typeConvertersLambda,
  ...);

Type conversion errors

If a url parameter cannot be converted to the specified type, the system will -- by default -- set the value to 0 or null, depending on if the type is nullable. However this behavior can be overwritten by implementing a lambda Function3<DeepLinkUri, Type, String, Integer> and setting it to typeConversionErrorNullable and/or typeConversionErrorNonNullable via the DeepLinkDelegate constructor. When called, the lambda will let you know about the matching DeepLinkUri template, the type and the value that was tried to type convert so you can also log these events.

Method Annotations

You can also annotate any public static method with @DeepLink. DeepLinkDispatch will call that method to create the Intent and will use it when starting your Activity via that registered deep link:

@DeepLink("foo://example.com/methodDeepLink/{param1}")
public static Intent intentForDeepLinkMethod(Context context) {
  return new Intent(context, MainActivity.class)
      .setAction(ACTION_DEEP_LINK_METHOD);
}

If you need access to the Intent extras, just add a Bundle parameter to your method, for example:

@DeepLink("foo://example.com/methodDeepLink/{param1}")
public static Intent intentForDeepLinkMethod(Context context, Bundle extras) {
  Uri.Builder uri = Uri.parse(extras.getString(DeepLink.URI)).buildUpon();
  return new Intent(context, MainActivity.class)
      .setData(uri.appendQueryParameter("bar", "baz").build())
      .setAction(ACTION_DEEP_LINK_METHOD);
}

If you're using Kotlin, make sure you also annotate your method with @JvmStatic. companion objects will not work, so you can use an object declaration instead:

object DeeplinkIntents {
  @JvmStatic 
  @DeepLink("https://example.com")
  fun defaultIntent(context: Context, extras: Bundle): Intent {
    return Intent(context, MyActivity::class.java)
  }
}

If you need to customize your Activity backstack, you can return a TaskStackBuilder instead of an Intent. DeepLinkDispatch will call that method to create the Intent from the TaskStackBuilder last Intent and use it when starting your Activity via that registered deep link:

@DeepLink("http://example.com/deepLink/{id}/{name}")
public static TaskStackBuilder intentForTaskStackBuilderMethods(Context context) {
  Intent detailsIntent =  new Intent(context, SecondActivity.class).setAction(ACTION_DEEP_LINK_COMPLEX);
  Intent parentIntent =  new Intent(context, MainActivity.class).setAction(ACTION_DEEP_LINK_COMPLEX);
  TaskStackBuilder  taskStackBuilder = TaskStackBuilder.create(context);
  taskStackBuilder.addNextIntent(parentIntent);
  taskStackBuilder.addNextIntent(detailsIntent);
  return taskStackBuilder;
}

If, depending on app state or parameter values you have to either just start an Intent or a TaskStackBuilder, you can return an instance of DeepLinkMethodResult, which can have any. The system will pick whichever value is not null but will prefer the TaskStackBuilder if both are not null.

@DeepLink("dld://host/methodResult/intent")
public static DeepLinkMethodResult intentOrTaskStackBuilderViaDeeplinkMethodResult(Context context) {
  TaskStackBuilder taskStackBuilder = null;
  Intent intent = null;
  if (someState) {
    Intent detailsIntent = new Intent(context, SecondActivity.class);
    Intent parentIntent = new Intent(context, MainActivity.class);
    taskStackBuilder = TaskStackBuilder.create(context);
    taskStackBuilder.addNextIntent(parentIntent);
    taskStackBuilder.addNextIntent(detailsIntent);
  } else {
    intent = new Intent(context, MainActivity.class);
  }
  return new DeepLinkMethodResult(intent, taskStackBuilder);
}

Query Parameters

Query parameters are parsed and passed along automatically, and are retrievable like any other parameter. For example, we could retrieve the query parameter passed along in the URI foo://example.com/deepLink?qp=123:

@DeepLink("foo://example.com/deepLink")
public class MainActivity extends Activity {
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    if (intent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false)) {
      Bundle parameters = intent.getExtras();
      if (parameters != null && parameters.getString("qp") != null) {
        String queryParameter = parameters.getString("qp");
        // Do something with the query parameter...
      }
    }
  }
}

Configurable path segment placeholders

Configurable path segment placeholders allow your to change configured elements of the URL path at runtime without changing the source of the library where the deeplink is defined. That way a library can be used in multiple apps that are still uniquely addressable via deeplinks. They are defined by encapsulating an id like this <some_id> and are only allowed as a path segment (between two slashes. /:

@DeepLink("foo://cereal.com/<type_of_cereal>/nutritional_info")
public static Intent intentForNutritionalDeepLinkMethod(Context context) {
  return new Intent(context, MainActivity.class)
      .setAction(ACTION_DEEP_LINK_METHOD);
}

If you do this you do have to provide a mapping (at runtime) for which values are allowed for creating a match. This is done when you new the DeeplinkDelegate class like:

@DeepLinkHandler({ AppDeepLinkModule.class, LibraryDeepLinkModule.class })
public class DeepLinkActivity extends Activity {
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Configure a map for configurable placeholders if you are using any. If you do a mapping
    // has to be provided for that are used
    Map configurablePlaceholdersMap = new HashMap();
    configurablePlaceholdersMap.put("type_of_cereal", "obamaos");
    // DeepLinkDelegate, LibraryDeepLinkModuleRegistry and AppDeepLinkModuleRegistry
    // are generated at compile-time.
    DeepLinkDelegate deepLinkDelegate = 
        new DeepLinkDelegate(new AppDeepLinkModuleRegistry(), new LibraryDeepLinkModuleRegistry(), configurablePlaceholdersMap);
    // Delegate the deep link handling to DeepLinkDispatch. 
    // It will start the correct Activity based on the incoming Intent URI
    deepLinkDelegate.dispatchFrom(this);
    // Finish this Activity since the correct one has been just started
    finish();
  }
}

This app will now match the Url foo://cereal.com/obamaos/nutritional_info to the intentForNutritionalDeepLinkMethod method for that app. If you build another app and set type_of_cereal to captnmaccains that apps version of the intentForNutritionalDeepLinkMethod would be called when when opening foo://cereal.com/captnmaccains/nutritional_info

If you are using configurable path segment placeholders, a mapping has to be provided for every placeholder used. If you are missing one the app will crash at runtime.

Empty configurable path segment placeholders mapping

A mapping can be to an empty string, in that case the element is just ignored. In the above example if configurablePlaceholdersMap.put("type_of_cereal", ""); is defined foo://cereal.com/nutritional_info would map to calling the intentForNutritionalDeepLinkMethod method. An empty configurable path segment placeholder is not allowed as the last path element in an URL!

Callbacks

You can optionally register a BroadcastReceiver to be called on any incoming deep link into your app. DeepLinkDispatch will use LocalBroadcastManager to broadcast an Intent with any success or failure when deep linking. The intent will be populated with these extras:

  • DeepLinkHandler.EXTRA_URI: The URI of the deep link.
  • DeepLinkHandler.EXTRA_SUCCESSFUL: Whether the deep link was fired successfully.
  • DeepLinkHandler.EXTRA_ERROR_MESSAGE: If there was an error, the appropriate error message.

You can register a receiver to receive this intent. An example of such a use is below:

public class DeepLinkReceiver extends BroadcastReceiver {
  private static final String TAG = "DeepLinkReceiver";

  @Override public void onReceive(Context context, Intent intent) {
    String deepLinkUri = intent.getStringExtra(DeepLinkHandler.EXTRA_URI);
    if (intent.getBooleanExtra(DeepLinkHandler.EXTRA_SUCCESSFUL, false)) {
      Log.i(TAG, "Success deep linking: " + deepLinkUri);
    } else {
      String errorMessage = intent.getStringExtra(DeepLinkHandler.EXTRA_ERROR_MESSAGE);
      Log.e(TAG, "Error deep linking: " + deepLinkUri + " with error message +" + errorMessage);
    }
  }
}

public class YourApplication extends Application {
  @Override public void onCreate() {
    super.onCreate();
    IntentFilter intentFilter = new IntentFilter(DeepLinkHandler.ACTION);
    LocalBroadcastManager.getInstance(this).registerReceiver(new DeepLinkReceiver(), intentFilter);
  }
}

Custom Annotations

You can reduce the repetition in your deep links by creating custom annotations that provide common prefixes that are automatically applied to every class or method annotated with your custom annotation. A popular use case for this is with web versus app deep links:

// Prefix all app deep link URIs with "app://airbnb"
@DeepLinkSpec(prefix = { "app://airbnb" })
// When using tools like Dexguard we require these annotations to still be inside the .dex files
// produced by D8 but because of this bug https://issuetracker.google.com/issues/168524920 they
// are not so we need to mark them as RetentionPolicy.RUNTIME.
@Retention(RetentionPolicy.RUNTIME)
public @interface AppDeepLink {
  String[] value();
}

You can use placeholders (like in paths) in the scheme and host section of prefixes listed in the DeepLinkSpec. e.g. if you want to match both http and https you can define it like this:

// Match all deeplinks which a scheme staring with "http".
@DeepLinkSpec(prefix = { "http{url_scheme_suffix}://airbnb.com")
@Retention(RetentionPolicy.CLASS)
public @interface WebDeepLink {
  String[] value();
}

You will get the value of url_scheme_suffix which -- in this case would be "" for http and "s" when https is used -- in the extras bundle of your annotated method. If you want to limit which values are accepted, you can do that directly within the placeholder by defining it with allowed values like this: http{url_scheme_suffix(|s)}://airbnb.com. In this case valid values would be "" and "s" (http and https). Values are pipe(|) separated, there can only be one (...) section per placeholder and it has to be at the end of the placeholder.

// Match all deeplinks which a scheme staring with "http".
@DeepLinkSpec(prefix = { "http{url_scheme_suffix(|s)}://{prefix(|www.)}airbnb.{domain(com|de)}")
@Retention(RetentionPolicy.CLASS)
public @interface WebDeepLink {
  String[] value();
}

The above code would match URLs that start with http or https, are for airbnb.com or airbnb.de or www.airbnb.com and www.airbnb.de. They would e.g. not match airbnb.ro.

// This activity is gonna handle the following deep links:
// "app://airbnb/view_users"
// "http://airbnb.com/users"
// "http://airbnb.com/user/{id}"
// "https://airbnb.com/users"
// "https://airbnb.com/user/{id}"
@AppDeepLink({ "/view_users" })
@WebDeepLink({ "/users", "/user/{id}" })
public class CustomPrefixesActivity extends AppCompatActivity {
    //...
}

This can be very useful if you want to use it with country prefxes in hostnames e.g.

// Match all deeplinks that have a scheme starting with http and also match any deeplink that
// starts with .airbnb.com as well as ones that are only airbnb.com
@DeepLinkSpec(prefix = { "http{url_scheme_suffix}://{country_prefix}.airbnb.com",
 "http{url_scheme_suffix}://airbnb.com")
@Retention(RetentionPolicy.CLASS)
public @interface WebDeepLink {
  String[] value();
}

which saves you from defining a lot prefixes.

Usage

Add to your project build.gradle file (Latest version is DeeplinkDispatch version ):

dependencies {
  implementation 'com.airbnb:deeplinkdispatch:x.x.x'
}

DeeplinkDispatch supports three ways to run the annotation processor dependin on which one you choose the setup is slightly different.

KSP

When using Kotlin we strongly suggest to use KSP as it can bring major speed improvements.

To run the processor via KSP you first have to apply the KSP plugin. Add the dependency to the build.gradle file of your main project:

buildscript {

    apply from: rootProject.file("dependencies.gradle")

    repositories {
        google()
        gradlePluginPortal()
    }
    dependencies {
        classpath "com.google.devtools.ksp:com.google.devtools.ksp.gradle.plugin:<ksp-version>"
    }
}

Apply the plugin in the build.gradle file of the project you want to use it:

plugins {
  id("com.google.devtools.ksp")
}

and don't forget the dependency to the annotation procesor and DeepLinkDispatch itself:

dependencies {
  implementation 'com.airbnb:deeplinkdispatch:x.x.x'
  ksp 'com.airbnb:deeplinkdispatch-processor:x.x.x'
}

Note: When using KSP (you have ksp 'com.airbnb:deeplinkdispatch-processor:x.x.x' in your dependencies) at least one Kotlin source file must be present in the project or no output will be generated!

As an example the main sample app is set up using KSP.

Kapt

If your project is already setup for Kotlin the only thing you have to add is the plugin:

plugins {
  id("kotlin-kapt")
}

and don't forget the dependency to the annotation procesor and DeepLinkDispatch itself:

dependencies {
  implementation 'com.airbnb:deeplinkdispatch:x.x.x'
  kapt 'com.airbnb:deeplinkdispatch-processor:x.x.x'
}

As an example the sample-kapt-library is set up using Kapt

Java annotation processor

Just add the dependency to DeepLinkDispatch and to the annotation processor:

dependencies {
  implementation 'com.airbnb:deeplinkdispatch:x.x.x'
  annotationProcessor 'com.airbnb:deeplinkdispatch-processor:x.x.x'
}

As an example the sample-library is set up using the Java annotation processor

When this is done, create your deep link module(s) (new on DeepLinkDispatch v3). For every class you annotate with @DeepLinkModule, DeepLinkDispatch will generate a "Registry" class, which contains a registry of all your @DeepLink annotations.

/** This will generate a AppDeepLinkModuleRegistry class */
@DeepLinkModule
public class AppDeepLinkModule {
}

Optional: If your Android application contains multiple modules (eg. separated Android library projects), you'll want to add one @DeepLinkModule class for every module in your application, so that DeepLinkDispatch can collect all your annotations in one "Registry" class per module:

/** This will generate a LibraryDeepLinkModuleRegistry class */
@DeepLinkModule
public class LibraryDeepLinkModule {
}

Create any Activity (eg. DeepLinkActivity) with the scheme you'd like to handle in your AndroidManifest.xml file (using foo as an example):

<activity
    android:name="com.example.DeepLinkActivity"
    android:theme="@android:style/Theme.NoDisplay">
    <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="foo" />
    </intent-filter>
</activity>

Annotate your DeepLinkActivity with @DeepLinkHandler and provide it a list of @DeepLinkModule annotated class(es):

@DeepLinkHandler({ AppDeepLinkModule.class, LibraryDeepLinkModule.class })
public class DeepLinkActivity extends Activity {
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // DeepLinkDelegate, LibraryDeepLinkModuleRegistry and AppDeepLinkModuleRegistry
    // are generated at compile-time.
    DeepLinkDelegate deepLinkDelegate = 
        new DeepLinkDelegate(new AppDeepLinkModuleRegistry(), new LibraryDeepLinkModuleRegistry());
    // Delegate the deep link handling to DeepLinkDispatch. 
    // It will start the correct Activity based on the incoming Intent URI
    deepLinkDelegate.dispatchFrom(this);
    // Finish this Activity since the correct one has been just started
    finish();
  }
}

of

@DeepLinkHandler({ AppDeepLinkModule.class, LibraryDeepLinkModule.class })
public class DeepLinkActivity extends Activity {
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Configure a map for configurable placeholders if you are using any. If you do a mapping
    // has to be provided for that are used
    Map configurablePlaceholdersMap = new HashMap();
    configurablePlaceholdersMap.put("your_values", "what should match");
    // DeepLinkDelegate, LibraryDeepLinkModuleRegistry and AppDeepLinkModuleRegistry
    // are generated at compile-time.
    DeepLinkDelegate deepLinkDelegate = 
        new DeepLinkDelegate(new AppDeepLinkModuleRegistry(), new LibraryDeepLinkModuleRegistry(), configurablePlaceholdersMap);
    // Delegate the deep link handling to DeepLinkDispatch. 
    // It will start the correct Activity based on the incoming Intent URI
    deepLinkDelegate.dispatchFrom(this);
    // Finish this Activity since the correct one has been just started
    finish();
  }
}

if you use configurable path segments

Upgrading

When upgrading to 5.x+ you may experience some breaking API changes. Read about them here.

Incremental annotation processing

You must update your build.gradle to opt into incremental annotation processing. When enabled, all custom deep link annotations must be registered in the build.gradle (pipe (|) separated), otherwise they will be silently ignored.

Examples of this configuration are as follows:

Standard

javaCompileOptions {
  annotationProcessorOptions {
    arguments = [
      'deepLink.incremental': 'true',
      'deepLink.customAnnotations': 'com.airbnb.AppDeepLink|com.airbnb.WebDeepLink'
    ]
  }
}

Kotlin kapt

kapt {
  arguments {
    arg("deepLink.incremental", "true")
    arg("deepLink.customAnnotations", "com.airbnb.AppDeepLink|com.airbnb.WebDeepLink")
  }
}

KSP

KSP is always incremental and you always have to provide the list of deepLink.customAnnotation if you have any or they will not be processed.

ksp {
  arg("deepLink.incremental", "true")
  arg("deepLink.customAnnotations", "com.airbnb.AppDeepLink|com.airbnb.WebDeepLink")
}

Performance

Starting with v5 DeeplinkDispatch is designed to be very fast in resolving deep links even if there are a lot of them. To ensure we do not regress from this benchmark tests using androidx.benchmark were added.

It is testing the ScaleTestActivity in the sample-benchmarkable-library which has 2000 deep links. For those on a Pixel 2 running Android 11 we expect the following results:

Started running tests

benchmark:        11,716 ns DeeplinkBenchmarks.match1
benchmark:       139,375 ns DeeplinkBenchmarks.match500
benchmark:     2,163,907 ns DeeplinkBenchmarks.newRegistry
benchmark:        23,035 ns DeeplinkBenchmarks.match1000
benchmark:       152,969 ns DeeplinkBenchmarks.match1500
benchmark:       278,906 ns DeeplinkBenchmarks.match2000
benchmark:       162,604 ns DeeplinkBenchmarks.createResultDeeplink1
benchmark:        11,774 ns DeeplinkBenchmarks.parseDeeplinkUrl
Tests ran to completion.

As you can see it takes us about 2ms to create the registry with 2000 entries. A lookup can be done in sub 1ms usually and createResult, which includes the lookup for the match1 case plus actually calling the method that was annotated, can be done in under 0.2ms.

The performance tests can be run from Android Studio or via gradle by running ./gradlew sample-benchmark:connectedCheck (with a device connected). The outoput can be found in sample-benchmark/build/outputs/connected_android_test_additional_output/.

Notes

  • Starting with DeepLinkDispatch v3, you have to always provide your own Activity class and annotate it with @DeepLinkHandler. It's no longer automatically generated by the annotation processor.
  • Intent filters may only contain a single data element for a URI pattern. Create separate intent filters to capture additional URI patterns.
  • Please refer to the sample app for an example of how to use the library.

Snapshots of the development version are available in Sonatype's snapshots repository.

To access the snapshots add this to your build.gradle file:

repositories {
    maven {
        url "https://oss.sonatype.org/content/repositories/snapshots/"
    }
}

Generated deep links Documentation

You can tell DeepLinkDispatch to generate text a document with all your deep link annotations, which you can use for further processing and/or reference. Note: Passing a fully qualified file path string as an argument to any compilation task will cause the cache key to be non-relocateable from one machine to another. In order to do that, add to your build.gradle file:

tasks.withType(JavaCompile) {
  options.compilerArgs << "-AdeepLinkDoc.output=${buildDir}/doc/deeplinks.txt"
}

When using Kotlin Kapt

kapt {
  arguments {
    arg("deepLinkDoc.output", "${buildDir}/doc/deeplinks.txt")
  }
}

and if you are using KSP

ksp {
  arg("deepLinkDoc.output", "${buildDir}/doc/deeplinks.txt")
}

The documentation will be generated in the following format:

* {DeepLink1}\n|#|\n[Description part of javadoc]\n|#|\n{ClassName}#[MethodName]\n|##|\n
* {DeepLink2}\n|#|\n[Description part of javadoc]\n|#|\n{ClassName}#[MethodName]\n|##|\n

You can also generate the output in a much more readable Markdown format by naming the output file *.md (e.g. deeplinks.md). Make sure that your Markdown viewer understands tables.

Matching and edge cases

Deeplink Dispatchs matching algo is designed to match non ambiguous structured URI style data very fast but because of the supported featureset it comes with some edge cases.

We organize the URI data (of all URIs that are in your app) in a tree structure that is created per module. The URI is dissolved into that tree structure and inserted into that graph at build time. We do not allow duplicates inside the tree at built time and having them will fail the build. However this is currently only guaranteed for each module not across modules.)

Example of a DeeplinkDispagch match graph

At runtime we traverse the graph for each module to find the correct action to undertake. The algo just walks the input URI until the last element and never backtracks inside the graph. The children of each element are checked for matches in alphabetic order:

elements without any variable element -> elements containing placeholders -> elements that are a configurable path segment

Edge cases

  • Duplicates can exist between modules. Only the first one found will be reported as a match. Modules are processed in the order the module registries are listed in your DeepLinkDelegate creation.
  • Placeholders can lead to duplications at runtime e.g. dld://airbnb/dontdupeme will match both @Deeplink('dld://airbnb/{qualifier}dupeme') and @Deeplink('dld://airbnb/dontdupeme'). They can both be defined in the same module as they are not identical. If they are defined in the same module the algo will match @Deeplink('dld://airbnb/dontdupeme') as it would check litereal matches before looking at elements containing placeholders. If they are not defined in the same module the one defined in the registry listed first in DeeplinkDelegate will be matched.
  • Configurable path segments can lead to duplicates. e.g. dld://airbnb/obamaos/cereal will match both @Deeplink('dld://airbnb/obamaos/cereal/') and @Deeplink('dld://airbnb/<brand>/cereal') if <brand> is configured to be obamaos. The same match rules as mentioned before apply here.
  • Configurable path segments can have empty values e.g. <brand> can be set to "" in the previous example. Which would then match dld://airbnb/cereal. If a deeplink like that is defined already somewhere else the same match rules as mentioned before apply to which match actually gets found.
  • Because of limitations of the algo the last path element (the item behind the last slash) cannot be a configurable path segment with it's value set to "". Currently the system will allow you to do this but will not correctly match in that case.

Proguard/R8 Rules

The Proguard/R8 rules mandatory for teh lib are defined in the proguard-rules.pro in deeplinkdispatch. However they are already included via consumerProguardFiles so there is nothing you have to do to include them.

Please note however that you must add your own Proguard/R8 rules to keep Custom annotations you have used. For example:

-keep @interface your.package.path.deeplink.<annotation class name>
-keepclasseswithmembers class * {
    @your.package.path.deeplink.<annotation class name> <methods>;
}

Testing the sample app

Use adb to launch deep links (in the terminal type: adb shell).

This fires a standard deep link. Source annotation @DeepLink("dld://example.com/deepLink")

am start -W -a android.intent.action.VIEW -d "dld://example.com/deepLink" com.airbnb.deeplinkdispatch.sample

This fires a deep link associated with a method, and also passes along a path parameter. Source annotation @DeepLink("dld://methodDeepLink/{param1}")

am start -W -a android.intent.action.VIEW -d "dld://methodDeepLink/abc123" com.airbnb.deeplinkdispatch.sample

You can include multiple path parameters (also you don't have to include the sample app's package name). Source annotation @DeepLink("http://example.com/deepLink/{id}/{name}")

am start -W -a android.intent.action.VIEW -d "http://example.com/deepLink/123abc/myname"

Note it is possible to call directly adb shell am ... however this seems to miss the URI sometimes so better to call from within shell.

License

Copyright 2015-2020 Airbnb, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

deeplinkdispatch's People

Contributors

adellhk avatar arpitanand avatar carvaq avatar cdeonier avatar chemouna avatar colinrtwhite avatar elihart avatar erickuck avatar felipecsl avatar gejiaheng avatar imlunacat avatar jingwei99 avatar jintin avatar joaquimley avatar kaedea avatar kxfang avatar lachlanmckee avatar mapyo avatar mgurreta avatar michaelevans avatar moyuruaizawa avatar mtiidla avatar nihk avatar petzel avatar renaudcerrato avatar rogerhu avatar rossbacher avatar runningcode avatar scottyab avatar zacsweers avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

deeplinkdispatch's Issues

Add deferred deep linking component

Hey team. Good stuff with this library!

What would you say if I added Branch as an optional component to call the dispatch on install if the user originated from a deep link? That way, folks can choose to add in a post-install deep linking component if they so choose.

I can it to the sample project and add some simple instructions on calling the dispatch directly. Plus, with Branch, they can create hosted URLs with custom deep link paths to complete the full circle integration from link -> dispatch.

Give me 👍 to proceed and I'll make PR or let me know your thoughts.

Subsequent deeplink doesn't work when App is launched from Deeplink?

In a textview I have some links which should when clicked tries to open a deeplink and this is handled by deeplinkdispatch and it works as expected. But when app is launched from deeplink the links which were in the textview doesn't work anymore.

What can I do to resolve this issue.
it gives following errors

I/Timeline: Timeline: Activity_launch_request id:com.example time:141468728
I/Timeline: Timeline: Activity_launch_request id:com.example time:141468741
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@2e1b4b34 time:141468837
I/Timeline: Activity_idle id: android.os.BinderProxy@31294bf4 time:141468837

Thanks,

Issue with Multiple Scheme

Hi

So I tried and tested the library for my android app. Everything worked fine. Then I had to enable multi dex due to 65K limit.

Now the deeplink won't open the target activity. Instead I would only see this in the console
I/MultiDex﹕ VM with version 2.1.0 has multidex support
I/MultiDex﹕ install
I/MultiDex﹕ VM has multidex support, MultiDex support library is disabled.

As a result, the app won't open at all.

EDIT: Please see the the updated issue in comment 5

Handle Uris with no host and params (e.g 'airbnb://')

Not sure if it's a bug or on purpose but DeepLinkDispatch does not handle Uris with just the base scheme, like airbnb://. In that case, DeepLinkUri.parse() with return ParseResult.INVALID_HOST. Not sure if we should handle it, any other thoughts?

Plans for release?

Hi all

I was wondering if you have any updates on release plans? I love the library, but am having trouble with user authentication using the DeepLinkActivity. Essentially, I want to be able to check if user is logged in before redirecting them to the relevant activity. I know that this was implemented in #87 and I see other places where you guys have spoken about version 1.6.0 and 2.0.0-SNAPSHOT, however when I try and update my build.gradle to use these version numbers it tells me they cannot be found. Am I missing something, or are they not yet available in Maven central? If you could let me know how to deal with this that would be great!

Cannot find DeepLinkDelegate

I am trying to use the 2.0.1 release of the library and want to use the @DeepLinkHandler class annotation. However, when I try and use the DeepLinkDelegate.dispatchFrom(this) method, Android Studio cannot find the DeepLinkDelegate class. My build.gradle class includes the following:

buildscript {
    dependencies {
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}

apply plugin: 'android-apt'

dependencies {
    compile 'com.airbnb:deeplinkdispatch:2.0.1'
    apt 'com.airbnb:deeplinkdispatch-processor:2.0.1'
}

In my activity I have the following:


@DeepLinkHandler
public class MyDeepLinkActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Some stuff
        DeepLinkDelegate.dispatchFrom(this);
        finish();
    }
}

Any ideas why this does not work, are there any known issues with the processor library? Or is it likely I am doing something wrong? Any help would be gratefully received .

Custom path matching regex

Currently I have seen that the regex (DeepLinkEntry.PARAM_VALUE) is "([a-zA-Z0-9_#!+%~,-.$]*)".
However I have url deeplinks that contains other characters, for example '&'.
https://www.mycompany.com/foo%20&%20bar

So they will not match.

The proposal is to allow the client to customize this regex. (Maybe using meta-data tag in the manifest?)

Thanks.

DeepLinkActivity not generated

I'm having some issues implementing this in my build. I've one successful build where DeepLinkActivity was generated, but most of the time it is not getting generated.

I have a few other apt libraries in my build so I wonder if that is causing conflicts?

Is there a way I can debug why DeepLinkActivity is not getting generated?

Deeplink loader class is incorrectly generated when project uses capital letters in Java package names

In the app I work on, we use capital letters in the package names, and DeeplinkDispatch incorrectly thinks that the package is a class, and that the actual activity is a nested class.

So, it generates DeepLinkLoader with "import com.example.Package"

and in the load() method:
new DeepLinkEntry("deeplink://path1", DeepLinkEntry.Type.CLASS, Package.Activity.class, null)

which fails to compile.

If I change that package name to small caps, then I can successfully compile the app, and the deeplinks work as well.

Could you please change the code to not automatically consider packages with capital letters as classes?

I believe the relevant code is in: ClassName.bestGuess() method, which is actually from squareup/javapoet

Static method to return Intent array

Currently, the static method needs to return a single Intent object

 public static Intent newIntent(Context context) {
        return new Intent(context, BlahActivity.class);
    }

Ideally, we'd like to be able to work with something like this:

    public static Intent[] newIntent(Context context) {
        return new Intent[] { newIntentOne(context), newIntentTwo(context) };
    }

Consider making the Callbacks more loosely coupled

Right now the only way to take advantage of the Callbacks is to implement the interface in your Application. Consider instead using an Intent with a specific signature that could be implemented in a Broadcast Receiver.

Dispatcher extension

Its is possible to do the boostrap or start up work such as app initialization and authentication in a central location (in the dispatcher) so that the activity which has the deep link does not have to take care of this.

Not prepared to handle parameters as "host"

DLD seems to assume that all templating happens on "path parameters", and never on the "host". (i.e. airbnb://foo/{bar} is valid, but airbnb://{bar} is not.)

Is this expected functionality (I don't think it's documented)? If not, I can try to put up a PR for the change.

Cannot apply into multi-modules project

The files generated by apt have the file names that are hard coded like following.

image

image

As a result, the library can only apply into the project owning only one module app. Otherwise, if applied into one main app and other depend library module, there would be more than one generated files with same names. And that would lead to dex error.

Would you please upgrade the current implementation to support multi-modules project?

Generate a class that includes all the Activity's deep link params

Right now you have to extract deep link parameters from the Intent extras, which is still pretty error prone since there is no compile time validation. We could leverage our annotation processor here to generate a class that contains all the Activity's deep link parameters, say FooActivity_DeepLink where you'd retrieve all the information from methods in this activity.

Deeplinkdispatch with Android Annotations - error creating file

I have a 1 activity project, with Android Annotations (using @EActivity to refer to the activity layout) and I am using DeeplinkDispatch on top of it

Seems like both annotations library don't go so well. If I remove either package, the app runs, but not with both

Only activity class

package com.example.android.deeplinktest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;


import com.airbnb.deeplinkdispatch.DeepLink;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;

@EActivity(R.layout.activity_main)
@DeepLink("foo://deepLink/{id}")
public class MainActivity extends AppCompatActivity {

/*    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);




    }*/


    @AfterViews
    public void init(){
        if (getIntent().getBooleanExtra(DeepLink.IS_DEEP_LINK, false)) {
            Bundle parameters = getIntent().getExtras();

            String idString = parameters.getString("id");

            ((TextView)findViewById(R.id.tv)).setText(idString);
        }
    }


}

Android Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.deeplinktest" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity_"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.airbnb.deeplinkdispatch.DeepLinkActivity"
            android:theme="@android:style/Theme.NoDisplay">
            <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="foo" />
            </intent-filter>
        </activity>


    </application>

</manifest>

build.gradle

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.example.android.deeplinktest"
        minSdkVersion 17
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

apt {
    arguments {
        androidManifestFile variant.outputs[0].processResources.manifestFile
        resourcePackageName "com.example.android.deeplinktest"
    }
}


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.1'
    compile 'com.airbnb:deeplinkdispatch:1.3.0'
    apt 'com.airbnb:deeplinkdispatch-processor:1.3.0'

    apt "org.androidannotations:androidannotations:3.2"
    compile 'org.androidannotations:androidannotations-api:3.2'

}

Error message

Information:Gradle tasks [clean, :app:compileDebugSources, :app:compileDebugAndroidTestSources]
:app:clean
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72221Library
:app:prepareComAndroidSupportSupportV42221Library
:app:prepareDebugDependencies
:app:compileDebugAidl
:app:compileDebugRenderscript
:app:generateDebugBuildConfig
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources
:app:mergeDebugResources
:app:processDebugManifest
:app:processDebugResources
:app:generateDebugSources
:app:processDebugJavaRes UP-TO-DATE
:app:compileDebugJava
Note: Resolve log file to /Users/somghosh/Programming/DeepLinkTest/app/build/generated/source/apt/androidannotations.log
Note: Initialize AndroidAnnotations 3.2 with options {androidManifestFile=/Users/somghosh/Programming/DeepLinkTest/app/build/intermediates/manifests/full/debug/AndroidManifest.xml, resourcePackageName=com.example.android.deeplinktest}
Note: Start processing for 2 annotations on 4 elements
Note: AndroidManifest.xml file found with specified path: /Users/somghosh/Programming/DeepLinkTest/app/build/intermediates/manifests/full/debug/AndroidManifest.xml
Warning:A class activity declared in the AndroidManifest.xml cannot be found in the compile path: [com.airbnb.deeplinkdispatch.DeepLinkActivity]
Note: AndroidManifest.xml found: AndroidManifest [applicationPackage=com.example.android.deeplinktest, componentQualifiedNames=[com.example.android.deeplinktest.MainActivity_], permissionQualifiedNames=[], applicationClassName=null, libraryProject=false, debugabble=false, minSdkVersion=17, maxSdkVersion=-1, targetSdkVersion=22]
Note: Found project R class: com.example.android.deeplinktest.R
Note: Found Android class: android.R
Note: Validating elements
Note: Validating with EActivityHandler: [com.example.android.deeplinktest.MainActivity]
Note: Validating with AfterViewsHandler: [init()]
Note: Processing root elements
Note: Processing root elements EActivityHandler: [com.example.android.deeplinktest.MainActivity]
Note: Processing enclosed elements
Note: Number of files generated by AndroidAnnotations: 1
Note: Writting following API classes in project: []
Note: Generating class: com.example.android.deeplinktest.MainActivity_
Note: Time measurements: [Whole Processing = 259 ms], [Extract Manifest = 178 ms], [Process Annotations = 32 ms], [Generate Sources = 18 ms], [Find R Classes = 14 ms], [Extract Annotations = 4 ms], [Validate Annotations = 4 ms], 
Note: Finish processing
Error:Error creating file
Note: Start processing for 0 annotations on 3 elements
Note: Time measurements: [Whole Processing = 0 ms], 
Note: Finish processing
Note: Start processing for 0 annotations on 0 elements
Note: Time measurements: [Whole Processing = 1 ms], 
Note: Finish processing
1 warning

Auto AndroidManifest entry

Why do we have to enter the Manifest Activity manually? Can't you just make it happen within the library thanks to Manifest merger.

Issues with deeplinks in the Sample app

Testing the sample app and finding some of the deep link are not resolving. I believe I am using the correct adb cmds and deeplinks defined in the sample? but I'd appreciate second pair of eyes.

The following work a-ok :)

adb shell am start -W -a android.intent.action.VIEW -d "dld://example.com/deepLink" com.airbnb.deeplinkdispatch.sample
adb shell am start -W -a android.intent.action.VIEW -d "http://example.com/fooScott" com.airbnb.deeplinkdispatch.sample

However these don't resolve intent :(

adb shell am start -W -a android.intent.action.VIEW -d "dld://classDeepLink?qp=123" com.airbnb.deeplinkdispatch.sample
adb shell am start -W -a android.intent.action.VIEW -d "dtd://host/somePath/54321" com.airbnb.deeplinkdispatch.sample
adb shell am start -W -a android.intent.action.VIEW -d "dld://classDeepLink" com.airbnb.deeplinkdispatch.sample
adb shell am start -W -a android.intent.action.VIEW -d "dld://methodDeepLink/abc123" com.airbnb.deeplinkdispatch.sample
adb shell am start -W -a android.intent.action.VIEW -d "dtd://example.com/deepLink/scottid123" com.airbnb.deeplinkdispatch.sample

I then wondered if it's because I had the action wrong, but adding the defined actions doesn't seem to help either.

adb shell am start -W -a deep_link_complex -d "dtd://host/somePath/54321" com.airbnb.deeplinkdispatch.sample
adb shell am start -W -a deep_link_method -d "dld://methodDeepLink/scottsparam" com.airbnb.deeplinkdispatch.sample

To confirm this is what I'm seeing output from adb

macbook:~ user$ adb shell am start -W -a android.intent.action.VIEW -d "dld://classDeepLink?qp=123" com.airbnb.deeplinkdispatch.sample
Starting: Intent { act=android.intent.action.VIEW dat=dld://classDeepLink?qp=123 pkg=com.airbnb.deeplinkdispatch.sample }
Error: Activity not started, unable to resolve Intent { act=android.intent.action.VIEW dat=dld://classDeepLink?qp=123 flg=0x10000000 pkg=com.airbnb.deeplinkdispatch.sample }

Proposal: Have DeepLinkDispatch supply its Proguard Rules

In a build.gradle we can have the deeplinkdepatch point to its own proguard rules like such.

android {
  defaultConfig {
    consumerProguardFiles 'consumer-proguard-rules.pro'
  }
}

This would require turning deeplinkdepatch into an android library project. Would this be something of interest or should this remain a java module?

Urls with # as an action are not matched

I have a case with this url : "http://www.example.com/#/{query}" but its not matched, i looked at the code and it's because encodedPath() in DeepLinkUri that looks for queries after ? or # .
int pathEnd = delimiterOffset(url, pathStart, url.length(), "?#");

Here's a failing test case for it :

  @Test public void urlWithHash() {
    DeepLinkEntry entry = deepLinkEntry("http://example.com/{any}/{nb}");  
                                         //or deepLinkEntry("http://example.com/#/{nb}");
    Map<String, String> parameters = entry.getParameters("http://example.com/#/2");
    assertThat(parameters.get("nb")).isEqualTo("2");
  }

is there a way to have an escape character or something for such a case ?

Thank you.

Merge parameters parsing and match in a single method

DeepLinkDispatch is not very memory efficient when it comes to matching the uris. Say that you have 20 entries, building the registry will parse 20 pattern in the constructor even if all the entries are not used. As a workaround, getParameters() and matches() could be merged and return a new object containing all the parsed uri details. That way there's no need to create a regex and set of parameters when building the DeepLinkEntry. In terms of code, that's how it would look like:

DeepLinkRegistry:

   public DeepLinkMatch parseUri(String uri) {
        for (DeepLinkEntry entry : registry) {
            final Optional<DeepLinkMatch> match = entry.matches(uri);
            if (match.isPresent()) {
                return match.get();
            }
        }

        return null;
    }

DeepLinkEntry:

   Optional<DeepLinkMatch> matches(String inputUri) {
        DeepLinkUri parsedUri = DeepLinkUri.parse(uri);
        String schemeHostAndPath = schemeHostAndPath(parsedUri);
        Set<String> parameters = parsePathParameters(parsedUri);
        Pattern regex = Pattern.compile(schemeHostAndPath.replaceAll(PARAM_REGEX, PARAM_VALUE) + "$");

        DeepLinkUri inputParsedUri = DeepLinkUri.parse(inputUri);
        boolean isMatch = inputParsedUri != null && regex.matcher(schemeHostAndPath(inputParsedUri)).find();

        if (isMatch) {
            Iterator<String> paramsIterator = parameters.iterator();
            Map<String, String> paramsMap = new ArrayMap<>(parameters.size());
            Matcher matcher = regex.matcher(schemeHostAndPath(inputParsedUri));
            int i = 1;
            if (matcher.matches()) {
                while (paramsIterator.hasNext()) {
                    String key = paramsIterator.next();
                    String value = matcher.group(i++);
                    if (value != null && !"".equals(value.trim())) {
                        paramsMap.put(key, value);
                    }
                }
            }
            return Optional.of(new DeepLinkMatch(this, paramsMap));

        } else {
            return Optional.absent();
        }
    }

DeepLinkMatch:

public class DeepLinkMatch {
    private final DeepLinkEntry entry;
    private final Map<String, String> parameters;

    public DeepLinkMatch(DeepLinkEntry entry, Map<String, String> parameters) {
        this.entry = entry;
        this.parameters = parameters;
    }

    public DeepLinkEntry getEntry() {
        return entry;
    }

    public Map<String, String> getParameters() {
        return parameters;
    }
}

Do you guys agree with that and should I work on a PR? It would require a few changes in the processor.

Parameters can't have '_' and '-' symbols, but should

I was about to use your library in my project, but it didn't recognize my url. As was found out, the regexp for parameters is too restrictive, as it forbids _ and - symbols.

My target url was like this:
someschema://somepath/an-identifier-with-dashes

Please, add this functionality.

Error:(42, 0) Gradle DSL method not found: 'apt()'

Dear,
when I add
compile 'com.airbnb:deeplinkdispatch:1.1.0'
apt 'com.airbnb:deeplinkdispatch-processor:1.1.0'

to gradle file, I face this error:
Error:(42, 0) Gradle DSL method not found: 'apt()'

I use gradle:
classpath 'com.android.tools.build:gradle:1.2.3'

Please advise.

Urls with spaces aren't matched

with a url that contains spaces for example that are replaced with "%20" doesn't get matched :
for example with a url http://www.example.com/action/search%20paris%20France%2092130" and with an annotation on an Activity like : @DeepLinks({"http://www.example.com/action/{searchAddress}"})
no match is found and DeepLinkEntry entry = registry.parseUri(uriString); in DeepLinkActivity always returns a null entry and so

   else {
      notifyListener(true, uri, "No registered entity to handle deep link: " + uri.toString());
      finish();
    }
   is called instead. 
is this not supported ? 

Thanks.

DeepLinkActivity didn't call finish() causing the app to crash

I'm trying the sample app with snapshot v2.0.0 of the library. Whenever I run the sample app through deeplink, it always crash. I think it's because the generated DeepLinkActivity class didn't call finish(). Here's the stack trace:

05-22 10:38:23.298 5482-5482/com.airbnb.deeplinkdispatch.sample W/Activity: An activity without a UI must call finish() before onResume() completes
05-22 10:38:23.299 5482-5482/com.airbnb.deeplinkdispatch.sample D/AndroidRuntime: Shutting down VM
05-22 10:38:23.300 5482-5482/com.airbnb.deeplinkdispatch.sample E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.airbnb.deeplinkdispatch.sample, PID: 5482
    java.lang.RuntimeException: Unable to resume activity {com.airbnb.deeplinkdispatch.sample/com.airbnb.deeplinkdispatch.DeepLinkActivity}: java.lang.IllegalStateException: Activity {com.airbnb.deeplinkdispatch.sample/com.airbnb.deeplinkdispatch.DeepLinkActivity} did not call finish() prior to onResume() completing
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3103)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3134)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2481)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5422)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.IllegalStateException: Activity {com.airbnb.deeplinkdispatch.sample/com.airbnb.deeplinkdispatch.DeepLinkActivity} did not call finish() prior to onResume() completing
        at android.app.Activity.performResume(Activity.java:6339)
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3092)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3134) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2481) 
        at android.app.ActivityThread.-wrap11(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:148) 
        at android.app.ActivityThread.main(ActivityThread.java:5422) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

Adding finish() statement in its onCreateMethod did the work.

Also, when will the new version be available in the JCenter repository? I can't wait to use it in my production app. 😄

DeepLink.IS_DEEP_LINK always equals false

getIntent().getBooleanExtra(DeepLink.IS_DEEP_LINK, false) returns always false, even when I open app from deeplink.

My annotation looks like @DeepLink("myapp://open")

My command to open deeplink am start -W -a android.intent.action.VIEW -d "myapp://open"

@DeepLinks stopped working

I discovered an issue with the @DeepLinks annotation in version 1.2.0. When using a single link with @DeepLink it works fine but as soon as I use @DeepLinks with multiple URIs it stops working and the DeepLinkLoader.java class is not generated anymore. Also, calling ./gradlew --stop and doing a clean build doesn't fix it.

Proguard rule for annotated methods

Hi,

I would like to ask you about proguard rule for annotated methods, which prepare intents.

-keepclasseswithmembers class * {
     public static android.content.Intent *(android.content.Context);
} 

works, but I would like to do it better using something similar to:

-keepclasseswithmembers class * {
     @com.airbnb.deeplinkdispatch.DeepLink <methods>;
} 

but it does not work - proguard removes unused methods.

What do I wrong?

Thank you in advance for answer and great library.

Best regards,
Jack

Firing a deep link with an unknown pathPrefix launches airbnb app

I have registered an Activity with e.g. @DeepLink("example://www.example.com/deepLink") and specified the custom scheme example in com.airbnb.deeplinkdispatch.DeepLinkActivity within AndroidManifest.xml. This works fine but
when I use a DeepLink with an unknown pathPrefix which is not registered e.g. example://www.example.com/someOtherLink with

adb shell am start -W -a android.intent.action.VIEW -d "example://www.example.com/someOtherLink" com.example.android

the airbnb app opens.

I think the problem is that an implicit intent is broadcasted in that case, since this DeepLinkEntry can't be found in the DeepLinkRegistry, and the airbnb app is handling the error case within DeepLinkReceiver, which launches airbnb's main activity.

Reading params collection

Library works fine with multiply params in URI?
example://example.com/deepLink?param1=123&param2=456&param3=789 ?
Right now I can get only first parameter.

Best regards,
Jack

Variable schemes across flavors

We have kind of a weird use case here - an app with three flavors and - of course - several activities, while one of the activity should deal with a certain set of URLs in one flavor and with another set of URLs in another. These URLs only differ in scheme and we already separated that out in the flavor's distinct manifests, i.e. we have DeepLinkActivity configured like this

  • src/flavor1/AndroidManifest.xml with <data android:scheme="ourscheme1" />
  • src/flavor2/AndroidManifest.xml with <data android:scheme="ourscheme2" />
  • ...

While this should work in general (because each flavor gets its own manifest and will therefor only react on URLs of its very scheme), its still a bit ugly to have to define all possible flavor combinations on the specific activity, i.e.

@DeepLink({"ourscheme1://some/path", "ourscheme2://some/path})
public class SomeActivity extends Activity { ... }

Is there any way around this? Would it be possible to just define the path, without the scheme?

Parent Stack in DeepLinkActivity

In the Generated DeepLinkActivity's class is it possible to handle parent Activity ?

Something like that :

TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
Class<?> currentClass = entry.getActivityClass();
while (hasParentActivity(currentClass)){
    stackBuilder.addParentStack(currentClass);
    currentClass = getParentActivity(currentClass);
}
stackBuilder.addNextIntent(intent);
startActivities(stackBuilder.getIntents());

if it's possible there is still a problem with the required parameter (intent extra) of the parent stack.
We should probably send the same extra parameter to the back stack ?

FYI from now i use NavUtils in every Deeplink activity

Android documentation :
http://developer.android.com/training/implementing-navigation/temporal.html#SynthesizeBackStack

LocalBroadcast Creates an NPE when sourceIntent's data Uri is null.

In the following code you can see that a null uri will be passed down to notifyListener and uri.toString() will be called on it.

public final class DeepLinkDelegate {

  // code

  public static DeepLinkResult dispatchFrom(Activity activity) {
    if (activity == null) {
      throw new NullPointerException("activity == null");
    }
    Intent sourceIntent = activity.getIntent();
    Uri uri = sourceIntent.getData();
    if (uri == null) {
      return createResultAndNotify(activity, false, null, "No Uri in given activity's intent.");
    }

    // Code
  }

  private static DeepLinkResult createResultAndNotify(Context context, final boolean successful, final Uri uri, final String error) {
    DeepLinkResult result = new DeepLinkResult(successful, uri, error);
    notifyListener(context, !successful, uri, error);
    return result;
  }

  private static void notifyListener(Context context, boolean isError, Uri uri, String errorMessage) {
    Intent intent = new Intent();
    intent.setAction(DeepLinkHandler.ACTION);
    intent.putExtra(DeepLinkHandler.EXTRA_URI, uri.toString());  // <-- NPE here
    intent.putExtra(DeepLinkHandler.EXTRA_SUCCESSFUL, !isError);
    if (isError) {
      intent.putExtra(DeepLinkHandler.EXTRA_ERROR_MESSAGE, errorMessage);
    }
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
  }
}

Support multiple schemes

Modify @DeepLink and @DeepLinks to also require the scheme:// in the URI definition, so we can suport more than one scheme in DeepLinkActivity.

deep link to handle production and test urls

In our project we have multiple test environments (to support our myriad and varied testing requirements) together with our production environment.

The current @deeplink annotation requires us to add a URL for every single environment:

@deeplink({
“https://prod_env/showDetail/detail.html”,
“https://test_env1/showDetail/detail.html”,
“https://test_env2/showDetail/detail.html”,
“https://test_env3/showDetail/detail.html”,
“https://test_env4/mock1/showDetail/detail.html”,
“https://test_env5/mock2/showDetail/detail.html”})
public class MyShowDetailActivity ….

This results in all our test environment annotations appearing in production code! It’s unwieldy and we have sometimes introduced new test environments, which would require code change on every activity that support deep linking to add the new environment.

We acknowledge that the intent filters within AndroidManifest.xml also need to be wordy (one entry per test env), but are pretty much taken care of by having separate manifests: debug/AndroidManifest.xml (many intent filter entries - one for each env) and release/AndroidManifest.xml (only one intent filter entry for the prod env).

Unfortunately this @deeplink java annotation can’t be as easily handled. We could try subclassing and annotate the debug subclass of MyShowDetailActivity for the debug build variant but that’s rather messy, just to get around the DeepLink annotation restriction.

Instead, if there was a variant of @deeplink that matched without hostname and scheme, that would allow us to do something simple and elegant such as:

@deeplink("/showDetail/detail.html”) // support all environments in a single hit and rely on intent filters to ensure the hostname or url prefix is correct
public class MyShowDetailActivity ….

So is it possible to enhance this library to handle this partial deep link match requirement?

Parameters regex should not match strings containing "/"

In my opinion this test should pass:

@Test public void multiplePathParams() {
    DeepLinkEntry entry = deepLinkEntry("airbnb://foos/{foo}");

    Map<String, String> parameters = entry.getParameters("airbnb://foos/baz/qux");
    assertThat(parameters)
      .isEmpty();
  }

but it's not. It finds the parameter foo with the value baz/qux.
The funny thing is that I can't repro with airbnb://{foo} and "airbnb://baz/qux".

Exclude some url path to open the apps?

hi,

I want to exclude some url path to prevent it open the apps because the content is not available for android app. below is my example url and action:

URL Action
http://www.example.com/ open app
http://www.example.com/path/to/content open app
http://www.example.com/pathto/content open app
http://www.example.com/pathtocontent open app
http://www.example.com/help do not open app
http://www.example.com/contactus do not open app

how can i achieve this using deeplinkdispatch?

I tried airbnb android app it can open app with below url:
https://www.airbnb.com.sg/
https://www.airbnb.com.sg/rooms/4516626
https://www.airbnb.com.sg/s/Seoul--South-Korea?source=ds

but not open:
https://www.airbnb.com.sg/getaways/Singapore?destination=Kuala-Lumpur
https://www.airbnb.com.sg/help

Method Annotations and getting parameter values

As with the example here, is there a way to fetch out the "param1" value, so that I can put it in the Intent as an extra with my own key/value pair?

@DeepLink("foo://example.com/methodDeepLink/{param1}")
public static Intent intentForDeepLinkMethod(Context context) {
  return new Intent(context, MainActivity.class).setAction(ACTION_DEEP_LINK_METHOD);
}

Thanks,
Jia

Proposal: Make generated DeepLinkActivity optional

The problem

Currently, all deeplink handling is done in a generated DeepLinkActivity that you must add to your manifest. While this is a convenient mechanism for easy dropping in, it's not very extensible if you have any requirements around your deeplinking. In particular, you ultimately don't control the entry point to your app, and can't run any sort of preconditions.

Example

Any app that has required login to proceed faces this issue. You receive a deeplink, check if the user is logged in, if yes then proceed, otherwise take them to the login screen. Unfortunately this doesn't allow for that kind of handling since there's no control over the generated activity. The dispatch gets done, regardless of the app state.

Proposed solutions

The generated DeepLinkActivity is actually well-suited to extraction to a class. My proposal is this: generate a Dispatcher class like the following:

public final class Dispatcher {
    public static DispatchResult dispatchFrom(Activity activity) {
        // Check activity != null...
        // Do all the dispatch handling...

        // Return the result
        return new DispatchResult(isError, uri, errorMessage);
    }
}

Where DispatchResult is a simple data class representing the information you'd otherwise send to the DeepLinkReceiver.

This would allow you to take advantage of the main benefit of the library (generated uri handling) while allowing you to keep control over entry points.

public class LaunchActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (isDeepLink() && requiredConditionsAreValid() && isLoggedIn()) {
            DispatchResult result = Dispatcher.dispatchFrom(this);

            if (!result.isSuccessful()) {
                // Do something about it
            else {
                // Done? Maybe? ¯\_(ツ)_/¯
                return;
            }
        }
    }
}

You could keep the currently existing implementation as well for convenience and just have it call through to the Dispatcher. This would also make it easy to test, especially if you opted for a new instance vs. static methods (which opens up easy injection and handling via Dagger/other DI implementations).

The alternative idea would be to add some form of precondition callback that the developer could register. This isn't as ideal though since it's fairly limited.

Names are totally up for discussion by the way! Curious to hear people's thoughts on this. If it's something you'd be for, can gladly contribute a PR for this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.