我在使用Activity时已经能够使用所有3种服务登录,但当我尝试更改为片段时,只要我在facebook / twitter上确认权限或点击谷歌登录按钮,应用程序就会关闭。没有错误,只是关闭。
我尝试调试“onActivityResult”(片段和活动),但没有调用它们。
我错过了什么吗?
活动:
public class SplashActivity extends FragmentActivity {
@BindView(R.id.splash_container)
RelativeLayout container;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
ButterKnife.bind(this);
new SecurePrefManagerInit.Initializer(getApplicationContext())
.useEncryption(true)
.initialize();
FragmentSplash fragmentSplash = new FragmentSplash();
final FragmentLogin fragmentLogin = new FragmentLogin();
//boolean dayNight = SecurePrefManager.with(this).get("night_mode").defaultValue(false).go();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean dayNight = sharedPreferences.getBoolean("night_mode", false);
if(!dayNight){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
addFragment(fragmentSplash);
}
private void addFragment(Fragment fragment){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.splash_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
private void replaceFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.splash_container, fragment)
//transaction.addToBackStack(null);
.disallowAddToBackStack();
transaction.commit();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.com_facebook_fragment_container);
fragment.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onPause() {
super.onPause();
finish();
}
}
片段:
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_login, container, false);
ButterKnife.bind(this, view);
mContext = getActivity();
loginFb = new LoginButton(getActivity());
loginFb.setFragment(this);
mLoginTwitter = new TwitterLoginButton(getActivity());
mCallbackManager = CallbackManager.Factory.create();
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() != null ) {
UtilsLibrary.showToastShort(mContext, "Logou");
//user = FirebaseAuth.getInstance().getCurrentUser();
Intent intent = new Intent(getActivity(), ChooseActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
getActivity().startActivity(intent);
} else {
UtilsLibrary.showToastShort(mContext, "Deslogou");
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(MyApp.getInstance().getApplicationContext())
.enableAutoManage(getActivity(), new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
UtilsLibrary.showToastLong(mContext, "Error");
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
return view;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setSharedElementEnterTransition(TransitionInflater.from(getContext()).inflateTransition(android.R.transition.move));
setEnterTransition(TransitionInflater.from(getContext()).inflateTransition(android.R.transition.fade));
}
}
public static FragmentLogin newInstance(){
FragmentLogin fragmentLogin = new FragmentLogin();
return fragmentLogin;
}
@OnClick(R.id.login_twitter_btn)
public void loginTwitter(View view){
signTwitter();
}
@OnClick(R.id.login_google_btn)
public void loginGoogle(View view){
signInGoogle();
}
@OnClick(R.id.logout_google_btn)
public void logOutAccounts(View view){
if(user != null){
mAuth.signOut();
switch (user.getProviders().get(0)){
case "google.com":
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
// ...
}
});
break;
case "facebook.com":
LoginManager.getInstance().logOut();
break;
case "twitter.com":
Twitter.logOut();
break;
}
}
}
@OnClick(R.id.login_facebook_btn)
public void loginFacebook(View view){
// startActivity(new Intent(this, ChooseActivity.class));
signFacebook();
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void signInGoogle(){
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
getActivity().startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void signTwitter(){
mLoginTwitter.setCallback(new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
// The TwitterSession is also available through:
// Twitter.getInstance().core.getSessionManager().getActiveSession()
TwitterSession session = result.data;
// TODO: Remove toast and use the TwitterSession's userID
// with your app's user model
handleTwitterSession(result.data);
String msg = "@" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
@Override
public void failure(TwitterException exception) {
Log.d("TwitterKit", "Login with Twitter failure", exception);
}
});
mLoginTwitter.callOnClick();
}
private void signFacebook(){
//LoginButton loginFb = new LoginButton(getActivity());
loginFb.setReadPermissions("email", "public_profile");
loginFb.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
@Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
// ...
}
@Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
// ...
}
});
loginFb.callOnClick();
}
private void handleTwitterSession(TwitterSession session){
AuthCredential credential = TwitterAuthProvider.getCredential(
session.getAuthToken().token,
session.getAuthToken().secret);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(mContext, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(mContext, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else {
Log.d(TAG, "onComplete: " + task.getResult().getUser().getDisplayName());
}
// ...
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (FacebookSdk.isInitialized()) {
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
mLoginTwitter.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// ...
}
}
}
private void firebaseAuthWithGoogle(final GoogleSignInAccount account) {
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
//Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
//Log.d(TAG, "signInWithCredential:onComplete:" + account.getGivenName());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
}
// ...
}
});
}
答案 0 :(得分:0)
使用此行将onActivityResult()
更新为此
片段片段=
getFragmentManager().findFragmentById(R.id.splash_container);
fragment.onActivityResult(requestCode, resultCode, data);
试试这个。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Fragment fragment =
getFragmentManager().findFragmentById(R.id.splash_container);
fragment.onActivityResult(requestCode, resultCode, data);
if (FacebookSdk.isInitialized()) {
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
mLoginTwitter.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// ...
}
}
}