Search code examples
androidandroid-intentandroid-activityintentfilter

How to dynamically register my activity to handle startActivity()?


I can statically register my activity to handle startActivity() by adding <intent-filter> in the manifest file. But how can I register it dynamically when my activity is running? For example, how can I register it after a button is clicked?

My application requires the user to specify a URL, and then I want to handle browsing requests to this URL. So I can only obtain this URL at run time. I looked at registerReceiver() only to find that it is only useful for sendBroadcast(), and not for startActivity().

In fact, I'm doing OAuth authentication with the server, and I want to return to my activity after OAuth. So I want to handle the <server-api-path>/auth/displaycode path.

I know that I can use a custom URL scheme and handle it statically in the manifest file, but according to 1, this is not a good practice.

After searching in the documents for an afternoon, I still can't figure this out. Any help is appreciated.


Solution

  • There is no API to dynamically register new Activity elements or modify the contents of the AndroidManifest at runtime. The best option for receiving an OAuth callback would be to implement a single Activity that contains a WebView, rather than launching the Browser or some external application and trying to return.

    With WebView you can monitor the URL traffic by attaching a WebViewClient, and using its methods like onPageStarted() and shouldOverrideUrlLoading() to determine when to jump back to the previous Activity or do some other action. Since you are doing all of this in code, the URL that you look for can be dynamic, even being passed in as an Intent extra to the Activity with the WebView

    HTH