Wednesday, 8 August 2012

Display an oAuth login webpage in a dialog

Objective


Display the login web page of an oAuth API in a dialog.

Issue


When you want to use an API with oAuth (like Facebook, Twitter, Instagram, ....), you need to redirect the user to the login webpage of the API. Unfortunately it opens the web browser and leaves your application, which might be disturbing for the user.

Solution

Steps
1. Create a layout with a WebView.
2. Create a DialogFragment and loads the previously created layout
3. Create a custom WebViewClient and override the shouldOverrideUrlLoading method to listen when a new URL is loaded and check when the login is successful.
4. Assign this custom WebViewClient to the WebView.
5. Display the dialog from your Activity.
Details
1. Create a layout with a webview oauth_screen.xml
   

<LinearLayout android:layout_gravity="center" android:layout_height="400dp" android:layout_width="320dp" android:minheight="400dp" android:minwidth="320dp" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">

    <WebView android:id="@+id/web_oauth" android:layout_height="400dp" android:layout_width="320dp">

</WebView></LinearLayout>


2. Create a DialogFragment and loads the previously created layout
3. Create a custom WebViewClient and override the shouldOverrideUrlLoading method to listen when a new URL is loaded and check when the login is successful.
4. Assign this custom WebViewClient to the WebView.


OAuthFragment.java
   
public class OAuthFragment extends DialogFragment {

    private WebView webViewOauth;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private static class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //check if the login was successful and the access token returned
            //this test depend of your API
            if (url.contains("access_token=")) {
                //save your token
                saveAccessToken(url);
                return true;
            }
            BaseActivity.logEvent(Consts.EVENT_CALLBACK + "Login Failed", true);
            return false;
        }
    }

    private void saveAccessToken(String url) {
        // extract the token if it exists
        String paths[] = url.split("access_token=");
        if (paths.length > 1) {
            ApplicationData.getInstance().setAccessToken(paths[1]);
            final SharedPreferences sharedPreferences = getActivity()
                    .getSharedPreferences(Consts.SHARED_PREFS_NAME, 0);
            final Editor edit = sharedPreferences.edit();
            edit.putString(Consts.KEY_ACCESS_TOKEN, paths[1]);
            edit.putBoolean(Consts.KEY_IS_LOGGED_OUT, false);
            edit.commit();

            Intent intent2 = new Intent(getActivity(), WallScreenActivity.class);
            intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent2);
            return;
        }
    }

    @Override
    public void onViewCreated(View arg0, Bundle arg1) {
        super.onViewCreated(arg0, arg1);
        try {
            //load the url of the oAuth login page
            webViewOauth
                    .loadUrl("https://xxxx.com/oauth/authorize/?");
            //set the web client
            webViewOauth.setWebViewClient(new MyWebViewClient());
            //activates JavaScript (just in case)
            WebSettings webSettings = webViewOauth.getSettings();
            webSettings.setJavaScriptEnabled(true);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        //Retrieve the webview
        View v = inflater.inflate(R.layout.oauth_screen, container, false);
        webViewOauth = (WebView) v.findViewById(R.id.web_oauth);
        getDialog().setTitle("Use your Instagram account");
        return v;
    }
}

MyActivity.java
 
    //Display the oAuth web page in a dialog
    void showDialog() {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.addToBackStack(null);

        // Create and show the dialog.
        OAuthFragment newFragment = new OAuthFragment();
        newFragment.show(ft, "dialog");
    }

3 comments:

  1. Fast and Furious 8 will be epic. I am so eagerly waiting for this movie since 2015. Paul walker will always stay in our heart. You can check out all the details regarding this movie from my site. #RIP Paul Walker. Fast and Furious 8 First Look

    ReplyDelete
  2. In the Windows 10 Anniversary Update, version 1607, Microsoft removed the on-off switch for Cortana. But the setting is still available if you know where to look more info here

    ReplyDelete