Android下使用最新FaceBook SDK 3.0(二)使用facebook实现登录注销

前一篇我们学习了集成FacebookSDK到我们项目工程中,这篇来学习一下如何使用facebook来登录!


1、打开 res/layout/activity_main.xml,在布局中添加一个facebook登录按钮

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <com.facebook.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="30dp"
        android:layout_marginTop="30dp" />
</LinearLayout>



2、 创建MainFragment 类,并且继承Fragment 类,

重写onCreateView()方法  

通过LoginButton设置权限 setReadPermissions()    更多权限访问 http://developers.facebook.com/docs/reference/login/#permissions

        重写 onSessionStateChange()方法  ,作用:当session状态改变时调用该方法,state.isOpened() 为 true 时,则证明登录成功!

package com.thirdfacebook;

import java.util.Arrays;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.LoginButton;

public class MainFragment extends Fragment {
	private static final String TAG = "MainFragment";
	private UiLifecycleHelper uiHelper;

	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		uiHelper = new UiLifecycleHelper(getActivity(), callback);
		uiHelper.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.activity_main, container, false);

		LoginButton authButton = (LoginButton) view
				.findViewById(R.id.login_button);
		authButton.setFragment(this);
		authButton.setReadPermissions(Arrays
				.asList("email","user_likes", "user_status"));
		return view;
	}

	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		if (state.isOpened()) {
			Log.i(TAG, "Logged in...");
		} else if (state.isClosed()) {
			Log.i(TAG, "Logged out...");
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();

		// For scenarios where the main activity is launched and user
		// session is not null, the session state change notification
		// may not be triggered. Trigger it if it's open/closed.
		Session session = Session.getActiveSession();
		if (session != null && (session.isOpened() || session.isClosed())) {
			onSessionStateChange(session, session.getState(), null);
		}

		uiHelper.onResume();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
	}
}


3、MainActivity 类 ,继承FragmentActivity类  ,初始化 添加MainFragment 类,打印哈希值可写可不写

package com.thirdfacebook;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends FragmentActivity {

	private MainFragment mainFragment;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (savedInstanceState == null) {
	        // Add the fragment on initial activity setup
	        mainFragment = new MainFragment();
	        getSupportFragmentManager()
	        .beginTransaction()
	        .add(android.R.id.content, mainFragment)
	        .commit();
	   } else {
	      // Or set the fragment from restored state info
	       mainFragment = (MainFragment) getSupportFragmentManager()
	       .findFragmentById(android.R.id.content);
	   }
		
		/**
		 * 打印哈希值
		 */
		try {
	        PackageInfo info = getPackageManager().getPackageInfo(
	                "com.firstfacebook", 
	                PackageManager.GET_SIGNATURES);
	        for (Signature signature : info.signatures) {
	            MessageDigest md = MessageDigest.getInstance("SHA");
	            md.update(signature.toByteArray());
	            Log.i("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
	            }
	    } catch (NameNotFoundException e) {

	    } catch (NoSuchAlgorithmException e) {

	    }
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
}

4、AndroidMainfest.xml 添加 facebook LoginActivity(登录activity)

<activity android:name="com.facebook.LoginActivity"/>

5、运行项目 成功运行后登录按钮变成Log Out, 点击Log Out则注销

Android下使用最新FaceBook SDK 3.0(二)使用facebook实现登录注销_第1张图片Android下使用最新FaceBook SDK 3.0(二)使用facebook实现登录注销_第2张图片


Android下使用最新FaceBook SDK 3.0(二)使用facebook实现登录注销_第3张图片Android下使用最新FaceBook SDK 3.0(二)使用facebook实现登录注销_第4张图片

参考自:http://developers.facebook.com/docs/howtos/androidsdk/3.0/login-with-facebook/


如果错误,望大牛多多指出!



你可能感兴趣的:(Android下使用最新FaceBook SDK 3.0(二)使用facebook实现登录注销)