Android 使用本机Facebook登录

Android 使用本机Facebook登录,android,facebook,Android,Facebook,我做了一个登录流程,无论是否安装了本机Facebook应用程序 我有以下代码: package com.xibio.everywhererun.facebook; import java.util.Arrays; import java.util.List; import com.facebook.AccessToken; import com.facebook.FacebookAuthorizationException; import com.facebook.FacebookOper

我做了一个登录流程,无论是否安装了本机Facebook应用程序

我有以下代码:

package com.xibio.everywhererun.facebook;


import java.util.Arrays;
import java.util.List;

import com.facebook.AccessToken;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.LoginButton;
import com.facebook.widget.ProfilePictureView;
import com.xibio.everywhererun.davide.R;
import com.xibio.everywhererun.history.HistoryDoneVsPlanned;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;




public class FbLoginActivity extends Activity{
//   private final String PENDING_ACTION_BUNDLE_KEY = "com.loginapptry.MainActivity:PendingAction"; //to understand well
   private static boolean isLogged; 

   //List of permissions probably only "publish actions" are needed for our app.   
   //As general rule the number of permissions must be the smallest possible
   private final List<String> listPermissions = Arrays.asList("publish_actions","user_actions.fitness");
   private LoginButton loginButton;                  
   private ProfilePictureView profilePictureView;    // is a customized view that displays the profile picture for a user.
   private TextView greeting;                      // display Hello "username"!
   private PendingAction pendingAction = PendingAction.NONE;
   private GraphUser user;   // is an interface that provides a strongly-typed
   private static final String  TAG = "FbLoginActivity";
   // representation of a Facebook user.

   private enum PendingAction {    //use to hold if any request are pending
      NONE, SHARE_RUN,TAKE_PIC
   }

   private UiLifecycleHelper uiHelper;      //This class helps to create, automatically open (if applicable),
   //save, and restore the Active Session in a way that is similar to Android UI lifecycles. 

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

   private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() { //Defines a callback interface that will be called when the user completes interacting with a Facebook dialog, or if an error occurs.

      @Override
      public void onError(FacebookDialog.PendingCall pendingCall,
            Exception error, Bundle data) {
         Log.d(TAG, "Callback Dialog"+ String.format("Error: %s", error.toString()));
      }

      @Override
      public void onComplete(FacebookDialog.PendingCall pendingCall,
            Bundle data) {
         Log.d(TAG, "Callback Dialog"+ "Success!");
      }
   };


   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      Log.i(TAG, "onCreate");
      uiHelper = new UiLifecycleHelper(this, callback);
      uiHelper.onCreate(savedInstanceState);

      Log.w(TAG, "accTok: "+Session.getActiveSession().getAccessToken());

      Log.w(TAG, Session.getActiveSession().toString());
      setContentView(R.layout.facebook_login);

      loginButton = (LoginButton) findViewById(R.id.login_button);
      loginButton.setPublishPermissions(listPermissions);


      //Sets the callback interface that will be called when the current user
      //changes. Obviously this callback is called by the System also when the user put credentials for the first time.
      loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
         @Override
         public void onUserInfoFetched(GraphUser user) {
            // GraphUser is an interface that provides a
            // strongly-typed representation of a Facebook user.
            FbLoginActivity.this.user = user;           
            updateUI();                      //update greetings (ie. Hello Dino) and user image picture probably is not needed in EWR
            // It's possible that we were waiting for this.user to
            // be populated in order to post a
            // status update.

         }
      });

      // is a customized view that displays the profile picture for a user.
      profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
      greeting = (TextView) findViewById(R.id.greeting);
      } 

   @Override
   protected void onResume() {
      super.onResume();
      uiHelper.onResume();
      Log.i(TAG, "onResume");
      Log.w(TAG,"accToken"+ Session.getActiveSession().getAccessToken());
      Log.w(TAG,"sesState: "+ Session.getActiveSession().getState().toString());
      Log.w(TAG, "Session"+Session.getActiveSession().toString());
      updateUI();
   }

   @Override
   protected void onSaveInstanceState(Bundle outState) {
      super.onSaveInstanceState(outState);
      uiHelper.onSaveInstanceState(outState);
//      outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
   }

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

   @Override
   public void onPause() {
      super.onPause();
      uiHelper.onPause();
      Log.i(TAG, "onPause: ");
      Log.w(TAG,"sessState: "+ Session.getActiveSession().getState().toString());
      Log.w(TAG, "Session: "+Session.getActiveSession().toString());
   }

   @Override
   public void onStop() {
      super.onStop();
      uiHelper.onStop();
      Log.i(TAG, "onStop");
      Log.w(TAG,"sessTate: "+ Session.getActiveSession().getState().toString());
      Log.w(TAG, "Session: " + Session.getActiveSession().toString());
      // savePreferencesData();
   }

   @Override
   public void onDestroy() {
      super.onDestroy();
      uiHelper.onDestroy();
      Log.i(TAG, "onDestroy");
      Log.w(TAG,"Sesstate: " + Session.getActiveSession().getState().toString());  
      Log.w(TAG, "Session: " + Session.getActiveSession().toString());
   }
  //rivedereeeeee 

  //Now for debug purpose
   private void onSessionStateChange(final Session session, SessionState state,Exception exception) {
       if(state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
           Log.i(TAG, "Session state change: "+state);
      }
      else if (state.equals(SessionState.OPENED)) { 
          Log.i(TAG, "Session state change: "+state);
          finish();
          return;
      }
      else if (state.equals(SessionState.OPENING)) {
          Log.i(TAG, "Session state change: "+state);
//       AccessToken accTok = AccessToken.createFromExistingAccessToken(session.getAccessToken(), null, null, null, listPermissions); 
//       Session.openActiveSessionWithAccessToken(FbLoginActivity.this, accTok, null);
      }
      else if(state.equals(SessionState.CLOSED_LOGIN_FAILED)) {
      Log.i(TAG, "Session state change: "+state);
      Toast.makeText(this, "Connectivity absent!", Toast.LENGTH_LONG).show();   //probably not only connectivity      
      }
      updateUI();
   }

   private void updateUI() { //update the user interface probably is not needed in EWR
      if (user != null) {
         profilePictureView.setProfileId(user.getId());
         greeting.setText(getString(R.string.hello_user, user.getFirstName()));
         isLogged=true;
      } else {
         profilePictureView.setProfileId(null);
         greeting.setText(null);
         isLogged=false;
      }
   }

   public  static boolean  isLogged() {
      return isLogged; 
    }
}
package com.xibio.everywhererun.facebook;
导入java.util.array;
导入java.util.List;
导入com.facebook.AccessToken;
导入com.facebook.facebook授权异常;
导入com.facebook.facebook操作取消异常;
导入com.facebook.Session;
导入com.facebook.SessionState;
导入com.facebook.ui生命周期帮助;
导入com.facebook.model.GraphUser;
导入com.facebook.widget.facebook对话框;
导入com.facebook.widget.LoginButton;
导入com.facebook.widget.ProfilePictureView;
导入com.xibio.everywhererun.davide.R;
导入com.xibio.everywhere run.history.history donevsplaned;
导入android.app.Activity;
导入android.app.AlertDialog;
导入android.content.Context;
导入android.content.Intent;
导入android.net.ConnectivityManager;
导入android.net.NetworkInfo;
导入android.os.Bundle;
导入android.support.v4.app.FragmentActivity;
导入android.util.Log;
导入android.widget.TextView;
导入android.widget.Toast;
公共类FbLoginActivity扩展了活动{
//private final String PENDING_ACTION_BUNDLE_KEY=“com.loginapptry.MainActivity:PendingAction”;//为了更好地理解
私有静态布尔值被记录;
//权限列表我们的应用程序可能只需要“发布操作”。
//一般来说,权限数必须尽可能少
private final List listPermissions=Arrays.asList(“发布动作”,“用户动作.适合度”);
私人登录按钮登录按钮;
private profile PictureView profile PictureView;//是为用户显示配置文件图片的自定义视图。
私有文本视图问候语;//显示问候语“用户名”!
私有PendingAction PendingAction=PendingAction.NONE;
私有GraphUser;//是一个提供强类型
私有静态最终字符串TAG=“FbLoginActivity”;
//Facebook用户的表示。
私有枚举挂起操作{//用于在任何请求挂起时保持
无,分享跑步,拍照
}
private UiLifecycleHelper uiHelper;//此类帮助创建、自动打开(如果适用),
//以类似于Android UI生命周期的方式保存和恢复活动会话。
private Session.StatusCallback callback=新建会话。StatusCallback(){//提供会话状态更改的异步通知。
@凌驾
公共无效调用(会话、会话状态、异常){
onSessionStateChange(会话、状态、异常);
}
};
private FacebookDialog.Callback dialogCallback=new FacebookDialog.Callback(){//定义一个回调接口,当用户完成与Facebook对话框的交互或发生错误时,将调用该接口。
@凌驾
public void onError(FacebookDialog.PendingCall PendingCall,
异常错误,捆绑数据){
Log.d(标记,“回调对话框”+String.format(“错误:%s”,错误.toString());
}
@凌驾
已完成的公共void(FacebookDialog.PendingCall PendingCall,
捆绑数据){
Log.d(标记“回调对话框”+“成功!”);
}
};
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Log.i(标记“onCreate”);
uiHelper=新UiLifecycleHelper(此为回调);
uiHelper.onCreate(savedInstanceState);
w(标记“accTok:+Session.getActiveSession().getAccessToken());
Log.w(标记,Session.getActiveSession().toString());
setContentView(R.layout.facebook_登录);
loginButton=(loginButton)findviewbyd(R.id.login_按钮);
setPublishPermissions(listPermissions);
//设置当前用户访问时将调用的回调接口
//显然,当用户第一次放置凭据时,系统也会调用此回调。
setUserInfoChangedCallback(新的loginButton.UserInfoChangedCallback(){
@凌驾
已获取公用void onUserInfo(GraphUser用户){
//GraphUser是一个提供
//Facebook用户的强类型表示。
FbLoginActivity.this.user=用户;
updateUI();//在EWR中可能不需要更新问候语(即Hello Dino)和用户图像图片
//有可能我们正在等待这个用户
//为了发布一个
//状态更新。
}
});
//是为用户显示配置文件图片的自定义视图。
profilePictureView=(profilePictureView)findViewById(R.id.profilePicture);
问候语=(TextView)findViewById(R.id.greeting);
} 
@凌驾
受保护的void onResume(){
super.onResume();
uiHelper.onResume();
Log.i(标签“onResume”);
Log.w(标记“accToken”+Session.getActiveSession().getAccessToken());
Log.w(标记“sesState:+Session.getActiveSession().getState().toString());
Log.w(标记“Session”+Session.getActiveSession().toString());
updateUI();
}
@凌驾
SaveInstanceState上受保护的无效(束超出状态){
super.onSaveInstanceState(超出状态);
uiHelper.onSaveInstanceState(outState);
//putString(PENDING_ACTION_BUNDLE_KEY,pendingAction.name());
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
onActivityResult(请求代码、结果代码、数据、对话框回调);
}
@凌驾
公共无效暂停(){
super.onPause();
uiHelper.onPause();
Log.i(标记“onPause:”);
w(标记“sessState:+Session.getActiveSession().getState().toString());
Log.w(标记“Session:+Session