Passing data to your PhoneGap Android app

For some situations it would be very convenient to be able to pass data from a website to your android app, even it has not yet been installed. The use case would be an app which provides customised content for a certain number of companies. You would like your app users to only see the content of the shops they have visited, but would like to avoid having to release one app per shop. Therefore you need to pass the identifier of the shop to your app when it is installed.

The solution is actually quite simple, here is how to do that:

The basic idea is to use cookies to store the information. The data flow is as follows:

open web page → set cookie → redirect to market → install app → launch browser with web page → read cookie → start custom intent with cookie data → capture intent and read cookie data

The user visits a webpage (by scanning a QR Tag for example). The url of the webpage holds a reference to the data you want to pass, or holds the data itself. The website sets the data as a cookie and redirects to the Android market (http://market.android.com/details?id=com.yourapp). As soon as your app launches, you open a browser and load the same webpage again. This time however, it detects that the cookie is already set and redirects to a custom URL scheme like example://example.com/installed?id=DATA, instead of the market. Using an intent filter, you launch your activity and extract the information from the intent.

Here is the relevant Activity code:

    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	Intent intent = getIntent();
    	if(intent == null || intent.getData() == null || !"example".equals(intent.getData().getScheme())) {
			String url = "http://example.com/yourApp/index.php";
			Intent i = new Intent(Intent.ACTION_VIEW);
			i.setData(Uri.parse(url));
			startActivity(i);
			finish();
			return;
    	}else {
    		Uri uri = intent.getData();
    		if("example".equals(uri.getScheme())) {
    			id = uri.getQueryParameter("id");
    		}
    	}
    	... initialise your activity ...
    }

A simple PHP file (the website) for easy demonstration:

    <?php
    $value = "123";
    if(!isset($_COOKIE["TestCookie"])) {
        setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
        header("Location: http://market.android.com/details?id=com.yourapp");
        exit;
    }else {
        header("Location: example://example.com/installed?id=".$_COOKIE["TestCookie"]);
        exit;
    }
    ?>

And the intent filter:

	<!-- Handle URLs like loyalty://example.com/merchant/123 -->
	<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="example" android:host="example.com" />
	</intent-filter>
I have also posted this solution on Stackoverflow.