Browser intent and return to correct activity (close opened tab)
I used the next approach to fix the same issue.
Let's assume we have MainActivity
with Sign In
button. Instead of starting browser directly clicking on that button I'm starting SignInActivity
using startActivityForResult
method. It's using for then I can handle result of login flow.
startActivityForResult(new Intent(this, SignInActivity.class), requestCode);
SignInActivity
is responsible for:
- open browser with login page
- catch redirect to
custom-scheme://callback
- finish login flow using token received from redirected url
- return result back to
MainActivity
So, its onCreate
method looks like:
@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); if (intent != null && intent.getData() != null && "custom-scheme".equals(intent.getData().getScheme())) { String code = getIntent().getData().getQueryParameter("code"); // complete oauth flow } else { Intent browserIntent = new Intent(Intent.ACTION_VIEW, "http://oauth2provider/authorize") .setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND); startActivity(browserIntent); finish(); }}
Admit flags set into the browser intent.
This way if SignInActivity
is opened from MainActivity
it just opens login page in the browser and if it's opened catching redirect url it completes login flow sending appropriate request.
After you complete login flow sending the code to some endpoint in your callback method you should do the following:
setResult(Activity.RESULT_OK);this.finish();
Naturally, you receive access_token from that endpoint. You can store it somewhere either here, in the success callback or return it back to the MainActivity
to handle it there.
As layout for SignInActivity
you can use just ProgressBar
in the center of the page. It will appear during login flow completion after SignInActivity
is opened caught redirect url (custom-scheme://callback
).
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ProgressBar android:layout_width="48dp" android:layout_height="48dp" android:layout_centerVertical="true" android:layout_centerHorizontal="true" /></RelativeLayout>
Here is declaration of SignInActivity
in AndroidManifest.xml
<activity android:name=".SignInActivity" android:launchMode="singleTask" android:noHistory="true" > <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="custom-scheme" android:host="callback"/> </intent-filter></activity>