Is there a way to pass a message from an Android browser to an app?

后端 未结 4 817
死守一世寂寞
死守一世寂寞 2021-02-05 22:27

I have a situation where I\'d like for some data to be passed from a mobile web site to a native Android app. A complication is that, in the normal case, the native Android app

4条回答
  •  执念已碎
    2021-02-05 23:10

    The solution is actually quite simple, I'm a bit astonished that nobody has been able to come up with it for over a year. So here it is:

    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:

    
    

    And the intent filter:

    
    
        
        
        
        
    
    

    BTW, I have decided to blog about the issue.

提交回复
热议问题