QQ和新浪帐号授权登录

package p.wy.hc.activity;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import p.wy.hc.bean.SharedPreferencesForLogin;
import p.wy.hc.util.JsonUtils;
import p.wy.hc.util.UpdateManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import cn.sharesdk.framework.AbstractWeibo;
import cn.sharesdk.framework.WeiboActionListener;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qzone.QZone;

/**
 * @author yangyu
 *	功能描述:获取用户资料
 * 
 * 启动页面时传递一个int类型的字段type,用于标记获取自己的资料(type = 0)还是别人的资料(type = 1)。
 * 如果尝试获取别人的资料,示例代码会获取不同平台Share SDK的官方帐号的资料。
 * 
 * 如果资料获取成功,会通过{@link ShowInforPage}展示
 */
public class MainActivity  extends Activity implements Callback, OnClickListener,WeiboActionListener {
	
	//定义标题栏布局对象
//	private TitleLayout llTitle;
	
	private Button sinaBt,qzoneBt,logonBt;
	
	private TextView user_phone,user_psw,user_reg;
	private Handler handler;
	
	Message message = null;  
	private static final int DISMISS_PROGRESS_DIALOG = 1;  
	private ProgressDialog progressDialog = null; 
	private Button nextBt;
	private String userName;
	private String userPsw;
	private String flag="false"; //true 为登录成功
	private SharedPreferencesForLogin spflusrinfo;
	private String url;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
			
		//初始化ShareSDK
		AbstractWeibo.initSDK(this);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		handler = new Handler(this);
		setContentView(R.layout.logon_main);
//		setContentView(R.layout.logonmain);
		spflusrinfo= new SharedPreferencesForLogin(MainActivity.this,"shared_prefsusrinfo"); //user logon type			
		initView();
		
		initData();
		
		// 检查软件更新
		UpdateManager manager = new UpdateManager(MainActivity.this);
		manager.checkUpdate();
		
		initUser();
	}
	//查看本地是否有用户信息,有的话直接跳转到主页
	public void initUser(){
		String userinfo=spflusrinfo.getValue("usrinfo");
		
	}
	/**
	 * 初始化组件
	 */
	private void initView(){
		//得到按钮对象
		/******
		sinaBt    = (Button) findViewById(R.id.sina_id);
		qzoneBt   = (Button) findViewById(R.id.qq_id);
		
		user_phone=(TextView)findViewById(R.id.user_phone_number);
		user_psw=(TextView)findViewById(R.id.user_phone_psw);
		user_reg=(TextView)findViewById(R.id.user_reg);
		logonBt=(Button)findViewById(R.id.logon_btn);
		*****/
		sinaBt    = (Button) findViewById(R.id.sina_logon);
		qzoneBt   = (Button) findViewById(R.id.qq_logon);
	
	}

	
	/**
	 * 初始化数据
	 */
	private void initData(){	
		//设置监听
		sinaBt.setOnClickListener(this);
		qzoneBt.setOnClickListener(this);
		
		/****
		user_phone.setOnClickListener(this);
		user_reg.setOnClickListener(this);
		logonBt.setOnClickListener(this);
		
		user_phone.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				user_phone.setBackgroundResource(R.drawable.aabb2);
				user_psw.setBackgroundResource(R.drawable.m);
			}
		});
		user_psw.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				user_psw.setBackgroundResource(R.drawable.aabb1);
				user_phone.setBackgroundResource(R.drawable.n);
				user_psw.setText("");
			}
		});
		*****/
		
	}
	
	/**
	 * 点击按钮获取授权用户的资料
	 */
	@Override
	public void onClick(View v) {
		String name = null;	
		switch (v.getId()) {
		case R.id.sina_logon:
			name = SinaWeibo.NAME;
			break;
		case R.id.qq_logon:
			name = QZone.NAME;
			break;
		/***************
		switch (v.getId()) {
		case R.id.sina_id:
			name = SinaWeibo.NAME;
			break;
		case R.id.qq_id:
			name = QZone.NAME;
			break;
			
		case R.id.user_phone_number:
			user_phone.setBackgroundResource(R.drawable.aabb2);
			user_psw.setBackgroundResource(R.drawable.m);
			user_phone.setText("");
			break;
//		case R.id.user_phone_psw:
//			user_psw.setBackgroundResource(R.drawable.aabb1);
//			user_phone.setBackgroundResource(R.drawable.n);
//			user_psw.setText("");
//			break;
		case R.id.user_reg:
			Intent intentreg = new Intent();
			intentreg.setClass(MainActivity.this, RegisterInfoActivity.class);
			startActivity(intentreg);
			break;
		case R.id.logon_btn:
			userName=user_phone.getText().toString();
			userPsw=user_psw.getText().toString();
			Toast.makeText(MainActivity.this, "登录",Toast.LENGTH_SHORT).show();
			/*****
			new Thread(runnablelogon).start();
			if(flag.equals("true")){
				//登录成功跳转
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, HealthCheckActivity.class);
				intent.putExtra("userName", userName);
				startActivity(intent);
			}else{
				//登录失败
				Toast.makeText(MainActivity.this, "登录失败",Toast.LENGTH_SHORT).show();
			}

			break;
			
			*****/
		}	
		
		if (name != null) {
			AbstractWeibo weibo = AbstractWeibo.getWeibo(this, name);
			weibo.setWeiboActionListener(this);
			String account = null;
			weibo.showUser(account);
			HealthCheckApplication hca=(HealthCheckApplication)this.getApplication();
			hca.weibo=weibo;
		}
	}

	/*****
	//登录验证
	private Runnable runnablelogon = new Runnable() {
		public void run() {
			Map<String, String> map = new HashMap<String, String>();
			map.put("username", userName);
			map.put("pwd", userPsw);
			map.put("dtype", "18");
			String result=HttpClientUtil.getResultData(CDefault.LOGON_URL, map);
			flag=FileUtil.getJSON(result, "authkey");  //true 为登录成功
			
		}
	};
	*****/
	public void onComplete(AbstractWeibo weibo, int action,HashMap<String, Object> res) {
		Message msg = new Message();
		msg.arg1 = 1;
		msg.arg2 = action;
		msg.obj = weibo;
		handler.sendMessage(msg);
		
		Message msg2 = new Message();
		if(weibo.getDb().getWeiboNname().equals("QZone")){
			msg2.what = 2;
		}else if(weibo.getDb().getWeiboNname().equals("SinaWeibo")){
			msg2.what = 1;
		}
		JsonUtils ju = new JsonUtils();
		String json = ju.fromHashMap(res);
		msg2.obj = ju.format(json);
		handler.sendMessage(msg2);
	}

	public void onError(AbstractWeibo weibo, int action, Throwable t) {
		t.printStackTrace();
		
		Message msg = new Message();
		msg.arg1 = 2;
		msg.arg2 = action;
		msg.obj = weibo;
		handler.sendMessage(msg);
	}

	public void onCancel(AbstractWeibo weibo, int action) {
		Message msg = new Message();
		msg.arg1 = 3;
		msg.arg2 = action;
		msg.obj = weibo;
		handler.sendMessage(msg);
	}
	
	/** 处理操作结果 */
	public boolean handleMessage(Message msg) {
		
		switch(msg.what) {
			case 1: {
				try {
					SharedPreferencesForLogin spflsina = new SharedPreferencesForLogin(this,"shared_prefssina");
					String userdata=spflsina.getValue("strsina");
					if(userdata!=null){
						Intent intent = new Intent();
						intent.setClass(MainActivity.this, HealthCheckActivity.class);
						String[] userInfo=userdata.split(",");
						intent.putExtra("userName", userInfo[0]);
						intent.putExtra("userIamage", userInfo[1]);
						url=userInfo[1];
						new ShowImgThread().start();
						//intent.putExtra("userIamage", userImg);
						intent.putExtra("weiboData", "SinaWeibo");
						spflusrinfo.putValue("Logon_Sina", "SinaWeibo");
						spflusrinfo.putValue("Logon_QQ", null);
						startActivity(intent);
					}else{
						Intent i = new Intent(this, ShowInforActivity.class);
						i.putExtra("data", String.valueOf(msg.obj));
						i.putExtra("weiboData", "SinaWeibo");
						spflusrinfo.putValue("Logon_Sina", "SinaWeibo");
						spflusrinfo.putValue("Logon_QQ", null);
						startActivity(i);
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
			break;
			case 2: {
				try {
					SharedPreferencesForLogin spflqq = new SharedPreferencesForLogin(this,"shared_prefsqq");
					String userdata=spflqq.getValue("strqq");
					if(userdata!=null){
						System.out.println(userdata); //直接跳转
						Intent intent = new Intent();
						intent.setClass(MainActivity.this, HealthCheckActivity.class);
						String[] userInfo=userdata.split(",");
						intent.putExtra("userName", userInfo[0]);
						intent.putExtra("userIamage", userInfo[1]);
						new ShowImgThread().start();
						intent.putExtra("weiboData", "QZone");
						//intent.putExtra("userIamage", userImg);
						spflusrinfo.putValue("Logon_Sina", null);
						spflusrinfo.putValue("Logon_QQ", "QZone");
						startActivity(intent);
						url=userInfo[1];
						new ShowImgThread().start();
					}else{
						Intent i = new Intent(this, ShowInforActivity.class);
						i.putExtra("data", String.valueOf(msg.obj));
						i.putExtra("weiboData", "QZone");
						spflusrinfo.putValue("Logon_Sina", null);
						spflusrinfo.putValue("Logon_QQ", "QZone");
						startActivity(i);
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
			break;
			default: {
				AbstractWeibo weibo = (AbstractWeibo) msg.obj;
				String text = MainActivity.actionToString(msg.arg2);
				switch (msg.arg1) {
					case 1: { // 成功
						text = weibo.getName() + " completed at " + text;
					}
					break;
					case 2: { // 失败
						text = weibo.getName() + " caught error at " + text;
					}
					break;
					case 3: { // 取消
						text = weibo.getName() + " canceled at " + text;
					}
					break;
				}
				//Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
			}
			break;
		}
		return false;
	}

	/**
	 * 将action转换为String
	 */
	public static String actionToString(int action) {
		switch (action) {
			case AbstractWeibo.ACTION_AUTHORIZING: return "ACTION_AUTHORIZING";
			case AbstractWeibo.ACTION_GETTING_FRIEND_LIST: return "ACTION_GETTING_FRIEND_LIST";
			case AbstractWeibo.ACTION_FOLLOWING_USER: return "ACTION_FOLLOWING_USER";
			case AbstractWeibo.ACTION_SENDING_DIRECT_MESSAGE: return "ACTION_SENDING_DIRECT_MESSAGE";
			case AbstractWeibo.ACTION_TIMELINE: return "ACTION_TIMELINE";
			case AbstractWeibo.ACTION_USER_INFOR: return "ACTION_USER_INFOR";
			case AbstractWeibo.ACTION_SHARE: return "ACTION_SHARE";
			default: {
				return "UNKNOWN";
			}
		}
	}
	
	
	/**监听对话框里面的button点击事件*/  
    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()  
    {  
        public void onClick(DialogInterface dialog, int which)  
        {  
            switch (which)  
            {  
            case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序  
            	finish();  
            	  //这里处理退出前跳到首个加载界面后执行下面的退出
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, MainActivity.class);
				startActivity(intent);
				// 退出程序
				Intent mHomeIntent = new Intent(
						Intent.ACTION_MAIN);
				mHomeIntent.addCategory(Intent.CATEGORY_HOME);
				mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
				startActivity(mHomeIntent);
				// 第二次关闭
				android.os.Process
				.killProcess(android.os.Process.myPid());

                break;  
            case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框  
                break;  
            default:  
                break;  
            }  
        }  
    };    
    @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event)  
    {  
        if (keyCode == KeyEvent.KEYCODE_BACK )  
        {  
            // 创建退出对话框  
            AlertDialog isExit = new AlertDialog.Builder(this).create();  
            // 设置对话框标题  
            isExit.setTitle("系统提示");  
            // 设置对话框消息  
            isExit.setMessage("确定要退出吗");  
            // 添加选择按钮并注册监听  
            isExit.setButton("确定", listener);  
            isExit.setButton2("取消", listener);  
            // 显示对话框  
            isExit.show();  
        }  
        return false;  
          
    }
    
    private class ShowImgThread extends Thread
    {
    	@Override
    	public void run()
    	{
    		Looper.prepare();

    		returnBitMap(url);

    		Looper.loop();
    	}

    };	
    //获取网络图片
    public void returnBitMap(String url) {   
    	URL myFileUrl = null;   
    	Bitmap bitmap = null;   
    	try {   
    		myFileUrl = new URL(url);   
    	} catch (MalformedURLException e) {   
    		e.printStackTrace();   
    	}   
    	try {   
    		if(myFileUrl!=null){
    			HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();   
    			conn.setDoInput(true);   
    			conn.connect();   
    			InputStream is = conn.getInputStream();   
    			bitmap = BitmapFactory.decodeStream(is);   
    			is.close();  
    		}
    	} catch (IOException e) {   
    		e.printStackTrace();   
    	}   
    	HealthCheckApplication applictaion=(HealthCheckApplication)this.getApplication();
    	
    	if(spflusrinfo.getValue("Logon_Sina")==null){
    		applictaion.mHeadBmQQ=bitmap;
    	}else{
    		applictaion.mHeadBmSina=bitmap;
    	}
//    	mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
    } 
}






源码下载地址 : http://www.32666.com/file-600256.html

猜你喜欢

转载自shangxun.iteye.com/blog/1964238
今日推荐