A while back I finally got a chance to dive into making an app with Appcelerator’s Titanium framework. Part of that task was trying to figure out how to add content uri support to the app. What that means is making your application aware of a certain content scheme. For example, a url. This of course could be expanded out to supporting your own content uri such as somethingawesome://do-something, mime types and few other methods.
I searched for quite awhile on this and found bits and pieces that helped in getting this accomplished but nothing from start to end. I tried a bunch of ways to get this done but nothing worked like I wanted. So here’s my attempt to make it easier for someone else.
For this example I’ll keep it simple by listening to a url of jeremymelton.com
First things first, open your tiapp.xml file.
In the android section of the file you’ll add an ‘activities’ section:
<data android:host="jeremymelton.com" android:scheme="http"/>
A few quick points here. Notice the url=”app.js” in the activity element. This could be any .js file you want to launch when the activity is started. For this example I wanted to launch the main app and parse the query string of the url.
The second point is the data element. This is letting Android know that we can handle a http link for jeremymelton.com using our activity(app.js). As mentioned earlier, there’s more you can do with the data element. I’ll leave that up to your investigation.
At this point when you click on a link to jeremymelton.com you will get an intent chooser popup asking if you want to use the browser or your app to open the link. If you choose your app…it will open your app.
Now, you’ll probably want to actually DO something when this happens. A very simple example we’ll grab the data of the intent, parse a querystring, then load a blog post by the post id in the url querystring.
In app.js (or whatever file you used for the activity url):
var activity = Ti.Android.currentActivity;
var intentData = activity.getIntent().getData();
getPost(intentData ? queryString(intentData, 'postID') : null);
To test this you’d click a link; jeremymelton.com?postID=1. You’d be prompted if you’d like to open this in the browser or your app. Click your app. The data from the getIntent().getData() call will contain http://jeremymelton.com?postID=1.
I grabbed a querystring function to parse out the querystring and voilà. We now have the postID of the link and can load a specific blog post.
And that’s it. Pretty simple to implement but potentially very powerful for your app.
The querystring function (original):
this.queryString = function (url, key)
var results = new RegExp('[\\?&]' + key + '=([^&#]*)').exec(url);
if (!results) return 0;
return results || null;