Repository: clayallsopp/routable-android Branch: master Commit: 053603f9f06d Files: 31 Total size: 53.7 KB Directory structure: gitextract_1hx1dx12/ ├── .classpath ├── .gitignore ├── .idea/ │ ├── .name │ ├── compiler.xml │ ├── copyright/ │ │ └── profiles_settings.xml │ ├── encodings.xml │ ├── gradle.xml │ ├── misc.xml │ ├── modules.xml │ └── vcs.xml ├── .project ├── AndroidManifest.xml ├── LICENSE ├── README.md ├── Routable.iml ├── RoutableTestTest/ │ ├── .classpath │ ├── .project │ ├── AndroidManifest.xml │ ├── proguard-project.txt │ ├── project.properties │ └── src/ │ └── com/ │ └── usepropeller/ │ └── routable/ │ └── test/ │ └── RouterTest.java ├── build.gradle ├── build.xml ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── proguard-project.txt ├── project.properties └── src/ └── com/ └── usepropeller/ └── routable/ ├── Router.java └── RouterActivity.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .classpath ================================================ ================================================ FILE: .gitignore ================================================ _site MANIFEST.MF ./*.jar build.num build local.properties bin/ gen/ _layouts .DS_Store gh-pages res/ .gradle /local.properties /.idea/workspace.xml /.idea/libraries .DS_Store /build ================================================ FILE: .idea/.name ================================================ Routable ================================================ FILE: .idea/compiler.xml ================================================ ================================================ FILE: .idea/copyright/profiles_settings.xml ================================================ ================================================ FILE: .idea/encodings.xml ================================================ ================================================ FILE: .idea/gradle.xml ================================================ ================================================ FILE: .idea/misc.xml ================================================ ================================================ FILE: .idea/modules.xml ================================================ ================================================ FILE: .idea/vcs.xml ================================================ ================================================ FILE: .project ================================================ Routable com.android.ide.eclipse.adt.ResourceManagerBuilder com.android.ide.eclipse.adt.PreCompilerBuilder org.eclipse.jdt.core.javabuilder com.android.ide.eclipse.adt.ApkBuilder com.android.ide.eclipse.adt.AndroidNature org.eclipse.jdt.core.javanature ================================================ FILE: AndroidManifest.xml ================================================ ================================================ FILE: LICENSE ================================================ Copyright (c) 2013 Turboprop, Inc. (http://usepropeller.com/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # Routable Routable is an in-app native URL router, for Android. Also available for [iOS](https://github.com/usepropeller/routable-ios). ## Usage Set up your app's router and URLs: ```java import com.usepropeller.routable.Router; public class PropellerApplication extends Application { @Override public void onCreate() { super.onCreate(); // Set the global context Router.sharedRouter().setContext(getApplicationContext()); // Symbol-esque params are passed as intent extras to the activities Router.sharedRouter().map("users/:id", UserActivity.class); Router.sharedRouter().map("users/new/:name/:zip", NewUserActivity.class); } } ``` In your `Activity` classes, add support for the URL params: ```java import com.usepropeller.routable.Router; public class UserActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle intentExtras = getIntent().getExtras(); // Note this extra, and how it corresponds to the ":id" above String userId = intentExtras.get("id"); } } public class NewUserActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle intentExtras = getIntent().getExtras(); // Corresponds to the ":name" above String name = intentExtras.get("name"); // Corresponds to the ":zip" above String zip = intentExtras.get("zip"); } } ``` *Anywhere* else in your app, open some URLs: ```java // starts a new UserActivity Router.sharedRouter().open("users/16"); // starts a new NewUserActivity Router.sharedRouter().open("users/new/Clay/94303"); ``` ## Installation Routable is currently an Android library project (so no Maven). If you're in a hurry, you can just copy-paste the [Router.java](https://github.com/usepropeller/routable-android/blob/master/src/com/usepropeller/routable/Router.java) file. Or if you're being a little more proactive, you should import the Routable project (this entire git repo) into Eclipse and [reference it](http://developer.android.com/tools/projects/projects-eclipse.html#ReferencingLibraryProject) in your own project. ## Features ### Routable Functions You can call arbitrary blocks of code with Routable: ```java Router.sharedRouter().map("logout", new Router.RouterCallback() { public void run(Router.RouteContext context) { User.logout(); } }); // Somewhere else Router.sharedRouter().open("logout"); ``` ### Open External URLs Sometimes you want to open a URL outside of your app, like a YouTube URL or open a web URL in the browser. You can use Routable to do that: ```java Router.sharedRouter().openExternal("http://www.youtube.com/watch?v=oHg5SJYRHA0") ``` ### Multiple Routers If you need to use multiple routers, simply create new instances of `Router`: ```java Router adminRouter = new Router(); Router userRouter = new Router(); ``` ## Contact Clay Allsopp ([http://clayallsopp.com](http://clayallsopp.com)) - [http://twitter.com/clayallsopp](http://twitter.com/clayallsopp) - [clay@usepropeller.com](clay@usepropeller.com) ## License Routable for Android is available under the MIT license. See the LICENSE file for more info. ================================================ FILE: Routable.iml ================================================ ================================================ FILE: RoutableTestTest/.classpath ================================================ ================================================ FILE: RoutableTestTest/.project ================================================ RoutableTest Routable com.android.ide.eclipse.adt.ResourceManagerBuilder com.android.ide.eclipse.adt.PreCompilerBuilder org.eclipse.jdt.core.javabuilder com.android.ide.eclipse.adt.ApkBuilder com.android.ide.eclipse.adt.AndroidNature org.eclipse.jdt.core.javanature ================================================ FILE: RoutableTestTest/AndroidManifest.xml ================================================ ================================================ FILE: RoutableTestTest/proguard-project.txt ================================================ # To enable ProGuard in your project, edit project.properties # to define the proguard.config property as described in that file. # # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in ${sdk.dir}/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the ProGuard # include property in project.properties. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ================================================ FILE: RoutableTestTest/project.properties ================================================ # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. # # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. target=android-7 android.library.reference.1=.. ================================================ FILE: RoutableTestTest/src/com/usepropeller/routable/test/RouterTest.java ================================================ package com.usepropeller.routable.test; import java.util.Map; import com.usepropeller.routable.Router; import junit.framework.Assert; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.test.AndroidTestCase; public class RouterTest extends AndroidTestCase { private boolean _called; @Override public void setUp() throws Exception { super.setUp(); this._called = false; } public void test_basic() { Router router = new Router(); router.map("users/:user_id", ListActivity.class); Intent intent = router.intentFor("users/4"); Assert.assertEquals("4", intent.getExtras().getString("user_id")); } public void test_empty() { Router router = new Router(); router.map("users", ListActivity.class); Intent intent = router.intentFor("users"); Assert.assertNull(intent.getExtras()); } public void test_invalid_route() { Router router = new Router(); boolean exceptionThrown = false; try { router.intentFor("users/4"); } catch (Router.RouteNotFoundException e) { exceptionThrown = true; } catch (Exception e) { e.printStackTrace(); fail("Incorrect exception throw: " + e.toString()); } Assert.assertTrue("Invalid route did not throw exception", exceptionThrown); } public void test_invalid_context() { Router router = new Router(); router.map("users", ListActivity.class); boolean exceptionThrown = false; try { router.open("users"); } catch (Router.ContextNotProvided e) { exceptionThrown = true; } catch (Exception e) { e.printStackTrace(); fail("Incorrect exception throw: " + e.toString()); } Assert.assertTrue("Invalid context did not throw exception", exceptionThrown); } public void test_code_callbacks() { Router router = new Router(this.getContext()); router.map("callback", new Router.RouterCallback() { @Override public void run(Router.RouteContext context) { RouterTest.this._called = true; Assert.assertNotNull(context.getContext()); } }); router.open("callback"); Assert.assertTrue(this._called); } public void test_code_callbacks_with_params() { Router router = new Router(this.getContext()); router.map("callback/:id", new Router.RouterCallback() { @Override public void run(Router.RouteContext context) { RouterTest.this._called = true; Assert.assertEquals("123", context.getParams().get("id")); } }); router.open("callback/123"); Assert.assertTrue(this._called); } public void test_code_callbacks_with_extras() { Router router = new Router(this.getContext()); router.map("callback/:id", new Router.RouterCallback() { @Override public void run(Router.RouteContext context) { RouterTest.this._called = true; Assert.assertEquals("value", context.getExtras().getString("test")); } }); Bundle extras = new Bundle(); extras.putString("test", "value"); router.open("callback/123", extras); Assert.assertTrue(this._called); } public void test_url_starting_with_slash() { Router router = new Router(); router.map("/users", ListActivity.class); Intent intent = router.intentFor("/users"); Assert.assertNull(intent.getExtras()); } public void test_url_querystring() { Router router = new Router(); router.map("/users/:id", ListActivity.class); Intent intent = router.intentFor("/users/123?key1=val2"); Bundle extras = intent.getExtras(); Assert.assertEquals("123", extras.getString("id")); Assert.assertEquals("val2", extras.getString("key1")); } public void test_url_containing_spaces() { Router router = new Router(); router.map("/path+entry/:id", ListActivity.class); Intent intent = router.intentFor("/path+entry/123"); Bundle extras = intent.getExtras(); Assert.assertEquals("123", extras.getString("id")); } public void test_url_querystring_with_encoded_value() { Router router = new Router(); router.map("/users/:id", ListActivity.class); Intent intent = router.intentFor("/users/123?key1=val+1&key2=val%202"); Bundle extras = intent.getExtras(); Assert.assertEquals("val 1", extras.getString("key1")); Assert.assertEquals("val 2", extras.getString("key2")); } public void test_url_querystring_without_value() { Router router = new Router(); router.map("/users/:id", ListActivity.class); Intent intent = router.intentFor("/users/123?val1"); Bundle extras = intent.getExtras(); Assert.assertTrue(extras.containsKey("val1")); } public void test_url_starting_with_slash_with_params() { Router router = new Router(); router.map("/users/:user_id", ListActivity.class); Intent intent = router.intentFor("/users/4"); Assert.assertEquals("4", intent.getExtras().getString("user_id")); } } ================================================ FILE: build.gradle ================================================ buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:1.2.3' } } apply plugin: 'android-library' repositories { mavenCentral() } android { compileSdkVersion 17 buildToolsVersion "19.1.0" defaultConfig { minSdkVersion 9 targetSdkVersion 17 } sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] res.srcDirs = ['res'] } androidTest { java.srcDir 'RoutableTestTest/src' } } } ================================================ FILE: build.xml ================================================ ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Wed Apr 10 15:27:10 PDT 2013 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip ================================================ FILE: gradlew ================================================ #!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # For Cygwin, ensure paths are in UNIX format before anything is touched. if $cygwin ; then [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` fi # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >&- APP_HOME="`pwd -P`" cd "$SAVED" >&- CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" ================================================ FILE: gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: proguard-project.txt ================================================ # To enable ProGuard in your project, edit project.properties # to define the proguard.config property as described in that file. # # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in ${sdk.dir}/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the ProGuard # include property in project.properties. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ================================================ FILE: project.properties ================================================ # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. # # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. target=android-17 android.library=true ================================================ FILE: src/com/usepropeller/routable/Router.java ================================================ /* Routable for Android Copyright (c) 2013 Turboprop, Inc. http://usepropeller.com Licensed under the MIT License. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.usepropeller.routable; import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; public class Router { private static final Router _router = new Router(); /** * A globally accessible Router instance that will work for * most use cases. */ public static Router sharedRouter() { return _router; } /** * The class used when you want to map a function (given in `run`) * to a Router URL. */ public static abstract class RouterCallback { public abstract void run(RouteContext context); } /** * The class supplied to custom callbacks to describe the route route */ public class RouteContext { Map _params; Bundle _extras; Context _context; public RouteContext(Map params, Bundle extras, Context context) { _params = params; _extras = extras; _context = context; } /** * Returns the route parameters as specified by the configured route */ public Map getParams() { return _params; } /** * Returns the extras supplied with the route */ public Bundle getExtras() { return _extras; } /** * Returns the Android Context that should be used to open the route */ public Context getContext() { return _context; } } /** * The class used to determine behavior when opening a URL. * If you want to extend Routable to handle things like transition * animations or fragments, this class should be augmented. */ public static class RouterOptions { Class _klass; RouterCallback _callback; Map _defaultParams; public RouterOptions() { } public RouterOptions(Class klass) { this.setOpenClass(klass); } public RouterOptions(Map defaultParams) { this.setDefaultParams(defaultParams); } public RouterOptions(Map defaultParams, Class klass) { this.setDefaultParams(defaultParams); this.setOpenClass(klass); } public void setOpenClass(Class klass) { this._klass = klass; } public Class getOpenClass() { return this._klass; } public RouterCallback getCallback() { return this._callback; } public void setCallback(RouterCallback callback) { this._callback = callback; } public void setDefaultParams(Map defaultParams) { this._defaultParams = defaultParams; } public Map getDefaultParams() { return this._defaultParams; } } private static class RouterParams { public RouterOptions routerOptions; public Map openParams; } private final Map _routes = new HashMap(); private String _rootUrl = null; private final Map _cachedRoutes = new HashMap(); private Context _context; /** * Creates a new Router */ public Router() { } /** * Creates a new Router * @param context {@link Context} that all {@link Intent}s generated by the router will use */ public Router(Context context) { this.setContext(context); } /** * @param context {@link Context} that all {@link Intent}s generated by the router will use */ public void setContext(Context context) { this._context = context; } /** * @return The context for the router */ public Context getContext() { return this._context; } /** * Map a URL to a callback * @param format The URL being mapped; for example, "users/:id" or "groups/:id/topics/:topic_id" * @param callback {@link RouterCallback} instance which contains the code to execute when the URL is opened */ public void map(String format, RouterCallback callback) { RouterOptions options = new RouterOptions(); options.setCallback(callback); this.map(format, null, options); } /** * Map a URL to open an {@link Activity} * @param format The URL being mapped; for example, "users/:id" or "groups/:id/topics/:topic_id" * @param klass The {@link Activity} class to be opened with the URL */ public void map(String format, Class klass) { this.map(format, klass, null); } /** * Map a URL to open an {@link Activity} * @param format The URL being mapped; for example, "users/:id" or "groups/:id/topics/:topic_id" * @param klass The {@link Activity} class to be opened with the URL * @param options The {@link RouterOptions} to be used for more granular and customized options for when the URL is opened */ public void map(String format, Class klass, RouterOptions options) { if (options == null) { options = new RouterOptions(); } options.setOpenClass(klass); this._routes.put(format, options); } /** * Set the root url; used when opening an activity or callback via RouterActivity * @param rootUrl The URL format to use as the root */ public void setRootUrl(String rootUrl) { this._rootUrl = rootUrl; } /** * @return The router's root URL, or null. */ public String getRootUrl() { return this._rootUrl; } /** * Open a URL using the operating system's configuration (such as opening a link to Chrome or a video to YouTube) * @param url The URL; for example, "http://www.youtube.com/watch?v=oHg5SJYRHA0" */ public void openExternal(String url) { this.openExternal(url, this._context); } /** * Open a URL using the operating system's configuration (such as opening a link to Chrome or a video to YouTube) * @param url The URL; for example, "http://www.youtube.com/watch?v=oHg5SJYRHA0" * @param context The context which is used in the generated {@link Intent} */ public void openExternal(String url, Context context) { this.openExternal(url, null, context); } /** * Open a URL using the operating system's configuration (such as opening a link to Chrome or a video to YouTube) * @param url The URL; for example, "http://www.youtube.com/watch?v=oHg5SJYRHA0" * @param extras The {@link Bundle} which contains the extras to be assigned to the generated {@link Intent} */ public void openExternal(String url, Bundle extras) { this.openExternal(url, extras, this._context); } /** * Open a URL using the operating system's configuration (such as opening a link to Chrome or a video to YouTube) * @param url The URL; for example, "http://www.youtube.com/watch?v=oHg5SJYRHA0" * @param extras The {@link Bundle} which contains the extras to be assigned to the generated {@link Intent} * @param context The context which is used in the generated {@link Intent} */ public void openExternal(String url, Bundle extras, Context context) { if (context == null) { throw new ContextNotProvided( "You need to supply a context for Router " + this.toString()); } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); this.addFlagsToIntent(intent, context); if (extras != null) { intent.putExtras(extras); } context.startActivity(intent); } /** * Open a map'd URL set using {@link #map(String, Class)} or {@link #map(String, RouterCallback)} * @param url The URL; for example, "users/16" or "groups/5/topics/20" */ public void open(String url) { this.open(url, this._context); } /** * Open a map'd URL set using {@link #map(String, Class)} or {@link #map(String, RouterCallback)} * @param url The URL; for example, "users/16" or "groups/5/topics/20" * @param extras The {@link Bundle} which contains the extras to be assigned to the generated {@link Intent} */ public void open(String url, Bundle extras) { this.open(url, extras, this._context); } /** * Open a map'd URL set using {@link #map(String, Class)} or {@link #map(String, RouterCallback)} * @param url The URL; for example, "users/16" or "groups/5/topics/20" * @param context The context which is used in the generated {@link Intent} */ public void open(String url, Context context) { this.open(url, null, context); } /** * Open a map'd URL set using {@link #map(String, Class)} or {@link #map(String, RouterCallback)} * @param url The URL; for example, "users/16" or "groups/5/topics/20" * @param extras The {@link Bundle} which contains the extras to be assigned to the generated {@link Intent} * @param context The context which is used in the generated {@link Intent} */ public void open(String url, Bundle extras, Context context) { if (context == null) { throw new ContextNotProvided( "You need to supply a context for Router " + this.toString()); } RouterParams params = this.paramsForUrl(url); RouterOptions options = params.routerOptions; if (options.getCallback() != null) { RouteContext routeContext = new RouteContext(params.openParams, extras, context); options.getCallback().run(routeContext); return; } Intent intent = this.intentFor(context, params); if (intent == null) { // Means the options weren't opening a new activity return; } if (extras != null) { intent.putExtras(extras); } context.startActivity(intent); } /* * Allows Intents to be spawned regardless of what context they were opened with. */ private void addFlagsToIntent(Intent intent, Context context) { if (context == this._context) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } } /** * @param url The URL; for example, "users/16" or "groups/5/topics/20" * @return The {@link Intent} for the url */ public Intent intentFor(String url) { RouterParams params = this.paramsForUrl(url); return intentFor(params); } private Intent intentFor(RouterParams params) { RouterOptions options = params.routerOptions; Intent intent = new Intent(); if (options.getDefaultParams() != null) { for (Entry entry : options.getDefaultParams().entrySet()) { intent.putExtra(entry.getKey(), entry.getValue()); } } for (Entry entry : params.openParams.entrySet()) { intent.putExtra(entry.getKey(), entry.getValue()); } return intent; } /** * @param url The URL to check * @return Whether or not the URL refers to an anonymous callback function */ public boolean isCallbackUrl(String url) { RouterParams params = this.paramsForUrl(url); RouterOptions options = params.routerOptions; return options.getCallback() != null; } /** * * @param context The context which is spawning the intent * @param url The URL; for example, "users/16" or "groups/5/topics/20" * @return The {@link Intent} for the url, with the correct {@link Activity} set, or null. */ public Intent intentFor(Context context, String url) { RouterParams params = this.paramsForUrl(url); return intentFor(context, params); } private Intent intentFor(Context context, RouterParams params) { RouterOptions options = params.routerOptions; if (options.getCallback() != null) { return null; } Intent intent = intentFor(params); intent.setClass(context, options.getOpenClass()); this.addFlagsToIntent(intent, context); return intent; } /* * Takes a url (i.e. "/users/16/hello") and breaks it into a {@link RouterParams} instance where * each of the parameters (like ":id") has been parsed. */ private RouterParams paramsForUrl(String url) { final String cleanedUrl = cleanUrl(url); URI parsedUri = URI.create("http://tempuri.org/" + cleanedUrl); String urlPath = parsedUri.getPath().substring(1); if (this._cachedRoutes.get(cleanedUrl) != null) { return this._cachedRoutes.get(cleanedUrl); } String[] givenParts = urlPath.split("/"); RouterParams routerParams = null; for (Entry entry : this._routes.entrySet()) { String routerUrl = cleanUrl(entry.getKey()); RouterOptions routerOptions = entry.getValue(); String[] routerParts = routerUrl.split("/"); if (routerParts.length != givenParts.length) { continue; } Map givenParams = urlToParamsMap(givenParts, routerParts); if (givenParams == null) { continue; } routerParams = new RouterParams(); routerParams.openParams = givenParams; routerParams.routerOptions = routerOptions; break; } if (routerParams == null) { throw new RouteNotFoundException("No route found for url " + url); } List query = URLEncodedUtils.parse(parsedUri, "utf-8"); for (NameValuePair pair : query) { routerParams.openParams.put(pair.getName(), pair.getValue()); } this._cachedRoutes.put(cleanedUrl, routerParams); return routerParams; } /** * * @param givenUrlSegments An array representing the URL path attempting to be opened (i.e. ["users", "42"]) * @param routerUrlSegments An array representing a possible URL match for the router (i.e. ["users", ":id"]) * @return A map of URL parameters if it's a match (i.e. {"id" => "42"}) or null if there is no match */ private Map urlToParamsMap(String[] givenUrlSegments, String[] routerUrlSegments) { Map formatParams = new HashMap(); for (int index = 0; index < routerUrlSegments.length; index++) { String routerPart = routerUrlSegments[index]; String givenPart = givenUrlSegments[index]; if (routerPart.charAt(0) == ':') { String key = routerPart.substring(1, routerPart.length()); formatParams.put(key, givenPart); continue; } if (!routerPart.equals(givenPart)) { return null; } } return formatParams; } /** * Clean up url * @param url * @return cleaned url */ private String cleanUrl(String url) { if (url.startsWith("/")) { return url.substring(1, url.length()); } return url; } /** * Thrown if a given route is not found. */ public static class RouteNotFoundException extends RuntimeException { private static final long serialVersionUID = -2278644339983544651L; public RouteNotFoundException(String message) { super(message); } } /** * Thrown if no context has been found. */ public static class ContextNotProvided extends RuntimeException { private static final long serialVersionUID = -1381427067387547157L; public ContextNotProvided(String message) { super(message); } } } ================================================ FILE: src/com/usepropeller/routable/RouterActivity.java ================================================ package com.usepropeller.routable; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; public class RouterActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String url; Bundle extras = intent.getExtras(); if (extras.containsKey("url")) { url = extras.getString("url"); } else { Uri data = intent.getData(); String protocol = data.getScheme() + "://"; url = data.toString().replaceFirst(protocol, ""); if (Router.sharedRouter().getRootUrl() != null) { Router.sharedRouter().open(Router.sharedRouter().getRootUrl()); } } Router.sharedRouter().open(url); setResult(RESULT_OK, null); finish(); } }