• 热门专题

使用WebView实现新浪微博OAuth登录

作者:chenfeng0104  发布日期:2011-09-20 13:13:34
Tag标签:WebView  新浪微博  
  • #新浪官方下载SDK(weibo4android)

    http://open.weibo.com/wiki/index.php/SDK

    #申请应用KEY

    登录新浪微博,进入http://open.weibo.com/申请应用,获取KEY和SECRET。

    #准备

    在项目中导入commons-httpclient-3.x.jar并加入weibo4android、weibo4android.http、weibo4android.org.json、weibo4android.util包文件和OAuthConstant.java文件(这些都是官方下载的SDK提供的文件)

    在跳转到新浪微博授权页面时会使用默认浏览器,这个不太好看,也有些用户手机用其他如UC等浏览器。因此,我决定用WebView代换默认浏览器。

    默认浏览器

     

    WebView代换

     

    在我的项目中,有多个应用项目需要OAuth登录,因此需要做成共通,也考虑到应用今后可能会支持如腾讯微博、人人网、支付宝等多种方式登录,所以我的代码考虑了“开-闭原则”。

     

    package com.oauth;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    
    public class ShareWithOAuthActivity extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            findViewById(R.id.share_button).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View button) {
                    OAuth.share(ShareWithOAuthActivity.this);
                }
            });
        }
    }
    package com.oauth;
    
    import android.app.AlertDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.widget.Toast;
    
    public class OAuth {
        public static final String SINA = "sina";
        public static final String TENCENT = "tencent";
        public static final String RENREN = "renren";
    
        private static AlertDialog alertDialog = null;
        private static String[] shareList = null;
        public static void share(final Context context) {
            if (shareList == null) {
                shareList = context.getResources().getStringArray(R.array.share_list);
            }
            if (alertDialog == null) {
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
                dialogBuilder.setTitle("分享");
                dialogBuilder.setItems(shareList, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int position) {
                        String flag = text2Flag(context, shareList[position]);
                        if (flag != null) {
                            oauthLogin(context, flag);
                        }
                    }
                });
                alertDialog = dialogBuilder.create();
            }
            alertDialog.show();
        }
        
        public static String text2Flag(Context context, String text) {
            String result = null;
            if ("分享到新浪微博".equals(text)) {
                result = SINA;
            } else if ("分享到腾讯微博".equals(text)) {
                result = TENCENT;
            } else if ("分享到人人网".equals(text)) {
                result = RENREN;
            } else {
                Toast.makeText(context, "没有匹配的类型", Toast.LENGTH_SHORT).show();
            }
            return result;
        }
        
        public static void oauthLogin(Context context, String flag) {
            Intent intent = new Intent();
            if (SINA.equals(flag)) {
                intent.setClass(context, SinaOAuth.class);
            } else if (TENCENT.equals(flag)) {
                //intent.setClass(context, TencentOAuth.class);
            } else if (RENREN.equals(flag)) {
                //intent.setClass(context, RenRenOAuth.class);
            }
            context.startActivity(intent);
        }
    }
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent">
      <TextView android:id="@+id/oauth_webview_title"
    	  android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:background="#996633"
          android:textColor="#000"
          android:textSize="18dp" />
      <WebView android:id="@+id/oauth_webview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
    </LinearLayout>
    package com.oauth;
    
    import weibo4android.http.AccessToken;
    import android.app.Activity;
    import android.os.Bundle;
    import android.webkit.WebView;
    import android.widget.TextView;
    
    public abstract class OAuthActivity extends Activity {
        protected static OAuthActivity oauthActivity;
        protected TextView titleView;
        protected WebView oauthWebView;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.oauth_webview_layout);
    
            initViews();
            oauthLogin();
        }
        
        private void initViews() {
            titleView = (TextView)findViewById(R.id.oauth_webview_title);
            
            oauthWebView = (WebView)findViewById(R.id.oauth_webview);
            oauthWebView.getSettings().setJavaScriptEnabled(true);
    //        oauthWebView.setWebViewClient(new WebViewClient() {
    //            @Override
    //            public boolean shouldOverrideUrlLoading(WebView view, String url) {
    //                return false;
    //            }
    //        });
        }
        
        protected abstract void oauthLogin();
        protected abstract void callback(AccessToken accessToken);
        
        public static void postLogin(AccessToken accessToken) {
            if (oauthActivity != null) {
                oauthActivity.callback(accessToken);
            }
            oauthActivity = null;
        }
    }
    package com.oauth;
    
    import weibo4android.Weibo;
    import weibo4android.WeiboException;
    import weibo4android.http.AccessToken;
    import weibo4android.http.RequestToken;
    import android.net.Uri;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.Toast;
    
    public class SinaOAuth extends OAuthActivity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            titleView.setText("新浪微博登录");
        }
    
        @Override
        protected void oauthLogin() {
            System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
            System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
            Weibo weibo = new Weibo();
            try {
                RequestToken requestToken =weibo.getOAuthRequestToken("weibo4android://CallbackActivity");
                OAuthConstant.getInstance().setRequestToken(requestToken);
                Uri uri = Uri.parse(requestToken.getAuthenticationURL()+ "&display=mobile");
                oauthWebView.loadUrl(uri.toString());//自定义WebView
            } catch (WeiboException e) {
                e.printStackTrace();
            }
            oauthActivity = this;//此处很关键
        }
    
        @Override
        public void callback(AccessToken accessToken) {
            Log.i("CDH", "SinaOAuth user id = "+accessToken.getUserId());
            Log.i("CDH", "SinaOAuth Token = "+accessToken.getToken());
            Log.i("CDH", "SinaOAuth Secret = "+accessToken.getTokenSecret());
            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
        }
    }
    package com.oauth;
    
    import weibo4android.WeiboException;
    import weibo4android.http.AccessToken;
    import weibo4android.http.RequestToken;
    import android.app.Activity;
    import android.net.Uri;
    import android.os.Bundle;
    
    public class CallbackActivity extends Activity {
    	
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    
    		try {
    		    RequestToken requestToken = OAuthConstant.getInstance().getRequestToken();
    		    Uri uri = this.getIntent().getData();
    			AccessToken accessToken = requestToken.getAccessToken(uri.getQueryParameter("oauth_verifier"));
    			OAuthConstant.getInstance().setAccessToken(accessToken);
    			OAuthActivity.postLogin(accessToken);
    			this.finish();
    		} catch (WeiboException e) {
    			e.printStackTrace();
    		}
    	}
    }
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.oauth"
          android:versionCode="1"
          android:versionName="1.0">
        <uses-sdk android:minSdkVersion="7" />
        <uses-permission android:name="android.permission.INTERNET" />
    
        <application android:icon="@drawable/icon" android:label="@string/app_name">
            <activity android:name=".ShareWithOAuthActivity"
                      android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity android:name=".CallbackActivity">
                <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="weibo4android" android:host="CallbackActivity" /> 
                </intent-filter>
            </activity>
            <activity android:name=".SinaOAuth" android:theme="@android:style/Theme.NoTitleBar" />
        </application>
    </manifest>
About IT165 - 广告服务 - 隐私声明 - 版权申明 - 免责条款 - 网站地图 - 网友投稿 - 联系方式
本站内容来自于互联网,仅供用于网络技术学习,学习中请遵循相关法律法规