2016-12-11 64 views
0

我試圖處理Facebook和谷歌登錄到一個單一的活動的Android - Facebook和谷歌登錄

在谷歌登錄作品,但Facebook登錄不顯示請求的權限對話框。當我點擊登錄Facebook按鈕時,我希望看到公共個人資料和電子郵件的權限對話框。儘管沒有出現對話框,但似乎我登錄時使用Facebook登錄更改爲註銷。有沒有更好的方法來做到這一點?

public class LoginActivity extends AppCompatActivity { 

    private static final String TAG = LoginActivity.class.getSimpleName(); 
    private static final int RC_SIGN_IN = 1; 
    private GoogleApiClient googleClient; 
    private CallbackManager callbackManager; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     FacebookSdk.sdkInitialize(getApplicationContext()); 
     setContentView(R.layout.activity_login); 


     callbackManager = CallbackManager.Factory.create(); 

     SignInButton googleButton = (SignInButton)findViewById(R.id.google_button); 
     LoginButton facebookBtn = (LoginButton)findViewById(R.id.fb_login_button); 
     Button emailButton = (Button)findViewById(R.id.email_button); 
     googleButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleClient); 
       startActivityForResult(signInIntent, RC_SIGN_IN); 
      } 
     }); 

     initGoogleSignIn(); 
     initFacebookSignIn(facebookBtn); 
    } 

    private boolean isLoggedInByFacebook(){ 
     AccessToken accessToken = AccessToken.getCurrentAccessToken(); 
     return accessToken != null; 
    } 

    private void initGoogleSignIn(){ 
     GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
       .requestIdToken(getString(R.string.default_web_client_id)) 
       .requestEmail() 
       .build(); 

     googleClient = new GoogleApiClient.Builder(this) 
       .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() { 
        @Override 
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 
        } 
       }) 
       .addApi(Auth.GOOGLE_SIGN_IN_API, gso) 
       .build(); 
     OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(googleClient); 
     if (opr.isDone()) { 
      // If the user's cached credentials are valid, the OptionalPendingResult will be "done" and the GoogleSignInResult will be available instantly. 
      Log.d("TAG", "Got cached sign-in"); 
      GoogleSignInResult result = opr.get(); 
      finish(); 
     } 

    } 

    private void initFacebookSignIn(LoginButton facebookBtn){ 
     if(isLoggedInByFacebook()) { 
      finish(); 
     }else{ 
      callbackManager = CallbackManager.Factory.create(); 
      facebookBtn.setReadPermissions(Arrays.asList(
        "public_profile","email")); 
      // Callback registration 
      facebookBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { 
       @Override 
       public void onSuccess(LoginResult loginResult) { 
        loginResult.getAccessToken().getUserId(); 
        // App code 
        GraphRequest request = GraphRequest.newMeRequest(
          loginResult.getAccessToken(), 
          new GraphRequest.GraphJSONObjectCallback() { 
           @Override 
           public void onCompleted(JSONObject object, GraphResponse response) { 
            try { 
             Log.i("Response",response.toString()); 
             String email = response.getJSONObject().getString("email"); 
             String name = response.getJSONObject().getString("name"); 
             finish(); 
            }catch (JSONException e){ 
             Log.e(TAG,"Error getting facebook email", e); 
            } 
           } 
          }); 
        Bundle parameters = new Bundle(); 
        parameters.putString("fields", "name,email"); 
        request.setParameters(parameters); 
        request.executeAsync(); 
       } 

       @Override 
       public void onCancel() { 
        // App code 
       } 
       @Override 
       public void onError(FacebookException exception) { 
        Log.e(TAG,"Error in facebook sign in", exception); 
       } 
      }); 
     } 
    } 

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == RC_SIGN_IN) { 
      GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); 
      if (result.isSuccess()) { 
       // Signed in successfully, show authenticated UI. 
       GoogleSignInAccount acct = result.getSignInAccount(); 
       api.loginGoogle(acct.getIdToken()).subscribe(new Action1<User>() { 
        @Override 
        public void call(User user) { 
         api.getWeather(-31.0, 115.0).subscribe(new Action1<WeatherResponse>() { 
          @Override 
          public void call(WeatherResponse weatherResponse) { 
          } 
         }); 
        } 
       }, new Action1<Throwable>() { 
        @Override 
        public void call(Throwable throwable) { 
         System.out.println(throwable); 
        } 
       }); 
      } else { 
       System.out.println(result.getStatus()); 
      } 
     }else { //facebook 
      callbackManager.onActivityResult(requestCode, resultCode, data); 
     } 
    } 

} 

回答

0

試試這個: 聲明變量:

private CallbackManager callbackManager; 
    private AccessTokenTracker accessTokenTracker; 
    com.facebook.Profile profile; 
    private ProfileTracker mProfileTracker; 
在onCreate()方法

..

FacebookSdk.sdkInitialize(getApplicationContext()); 
    callbackManager = CallbackManager.Factory.create(); 
    updateWithToken(AccessToken.getCurrentAccessToken()); 
    accessTokenTracker = new AccessTokenTracker() { 
     @Override 
     protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) { 
      updateWithToken(newToken); 
     } 
    }; 
    accessTokenTracker.startTracking(); 
在updateWithToken

NOW()方法

private void updateWithToken(AccessToken currentAccessToken) { 

    if (currentAccessToken != null) { 
     LoginManager.getInstance().logOut(); 
    } else { 
    } 
} 

現在在回調中經理,你必須跟蹤用戶的當前配置文件

List<String> permissionNeeds = Arrays.asList(
      "public_profile", "email", "user_birthday", "user_friends"); 
    loginButton.setReadPermissions(permissionNeeds); 

    loginButton.registerCallback(callbackManager, 
      new FacebookCallback<LoginResult>() { 
       @Override 
       public void onSuccess(LoginResult loginResult) { 
        Log.d("Success", "Login"); 
        try { 
         if (Profile.getCurrentProfile() == null) { 
          mProfileTracker = new ProfileTracker() { 
           @Override 
           protected void onCurrentProfileChanged(Profile profile_old, Profile profile_new) { 
            // profile2 is the new profile 
            profile = profile_new; 
            if (profile_new != null) 
             Log.v("facebook - profile", profile_new.getFirstName()); 
            mProfileTracker.stopTracking(); 
           } 
          }; 
          mProfileTracker.startTracking(); 

         } else { 
          profile = Profile.getCurrentProfile(); 
          if (profile != null) 
           Log.v("facebook - profile", profile.getFirstName()); 
         } 

         GraphRequest request = GraphRequest.newMeRequest(
           loginResult.getAccessToken(), 
           new GraphRequest.GraphJSONObjectCallback() { 
            @Override 
            public void onCompleted(JSONObject object, GraphResponse response) { 
             // Application code 
             try { 
              Log.v("FACEBOOK LOGIN", response.toString()); 
              fb_id = object.getString("id"); 
              fb_name = object.getString("name"); 
              fb_gender = object.getString("gender"); 
              fb_email = object.getString("email"); 
              fb_birthday = object.getString("birthday"); 
             } catch (Exception e) { 
              e.printStackTrace(); 
              Log.d("Error", e.toString()); 
            } 
           }); 
         Bundle parameters = new Bundle(); 
         parameters.putString("fields", "id,name,email,gender,birthday,picture.type(small)"); 
         request.setParameters(parameters); 
         request.executeAsync(); 

        } catch (Exception e) { 
         Log.d("ERROR", e.toString()); 
        } 
       } 

       @Override 
       public void onCancel() { 
        Log.d("FACEBOOK ERRROR", "cancelled"); 
       } 

       @Override 
       public void onError(FacebookException exception) { 
        Log.d("FACEBOOK ERRROR", exception.toString()); 
      }); 
+0

沒有更新?它有效嗎? – rafsanahmad007