我在这里陷入困境。
用户可以使用其FB帐户登录。该应用会创建一个具有相同信息的Firebase用户。
使用启动器活动(LoginActivity),如果它检测到用户已经登录,则会将其重定向到其配置文件片段。
LogOut方法(在MainFrag中)
public void LogOut(){
Log.d(TAG, "CHECK #2: USER SIGNED OUT");
getActivity().getIntent().removeExtra("user_id");
getActivity().getIntent().removeExtra("profile_picture");
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
Log.d(TAG, "signed out" + mUser.getUid());
// mAuth.unauth();
Intent intent = new Intent(getActivity().getApplicationContext(),
LoginActivity.class);
myFirebaseRef.unauth();
LoginManager.getInstance().logOut();
startActivity(intent);
Log.d(TAG, "CHECK 3: FINISIHED SIGNED OUT");
Log.d(TAG, "onAuthStateChanged:signed_out");
}
LoginActivity
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "AndroidBash";
public User user;
private EditText email;
private EditText password;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private ProgressDialog mProgressDialog;
private DatabaseReference mDatabase;
//Add YOUR Firebase Reference URL instead of the following URL
private Firebase mRef=new Firebase("https://fitmaker-ee2c0.firebaseio.com/");
//FaceBook callbackManager
private CallbackManager callbackManager;
//
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Log.d(TAG, "CHECK - FB SIGN IN - USER IS LOGGED IN " + mUser.getUid());
Intent intent = new Intent(getApplicationContext(), CustomColorActivity.class);
String uid = mAuth.getCurrentUser().getUid();
String image=mAuth.getCurrentUser().getPhotoUrl().toString();
intent.putExtra("user_id", uid);
if(image!=null || image!=""){
intent.putExtra("profile_picture",image);
}
startActivity(intent);
finish();
Log.d(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
}
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser mUser = firebaseAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
//FaceBook
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
signInWithFacebook(loginResult.getAccessToken());
}
@Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
}
@Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
}
});
//
}
@Override
protected void onStart() {
super.onStart();
email = (EditText) findViewById(R.id.edit_text_email_id);
password = (EditText) findViewById(R.id.edit_text_password);
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
//FaceBook
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
//
protected void setUpUser() {
user = new User();
user.setEmail(email.getText().toString());
user.setPassword(password.getText().toString());
}
public void onSignUpClicked(View view) {
Intent intent = new Intent(this, SignUpActivity.class);
startActivity(intent);
}
public void onLoginClicked(View view) {
setUpUser();
signIn(email.getText().toString(), password.getText().toString());
}
private void signIn(String email, String password) {
Log.d(TAG, "signIn:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithEmail: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, "signInWithEmail", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
String uid = mAuth.getCurrentUser().getUid();
intent.putExtra("user_id", uid);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
//
}
private boolean validateForm() {
boolean valid = true;
String userEmail = email.getText().toString();
if (TextUtils.isEmpty(userEmail)) {
email.setError("Required.");
valid = false;
} else {
email.setError(null);
}
String userPassword = password.getText().toString();
if (TextUtils.isEmpty(userPassword)) {
password.setError("Required.");
valid = false;
} else {
password.setError(null);
}
return valid;
}
private void signInWithFacebook(AccessToken token) {
Log.d(TAG, "signInWithFacebook:" + token.getToken());
showProgressDialog();
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, 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(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}else{
String uid=task.getResult().getUser().getUid();
String name=task.getResult().getUser().getDisplayName();
String email=task.getResult().getUser().getEmail();
String image=task.getResult().getUser().getPhotoUrl().toString();
//Create a new User and Save it in Firebase database
User user = new User(uid,name,null,email,name);
user = new User();
// user.setId(authData.getUid());
user.setName(name);
user.setEmail(email);
user.saveUser();
// mRef.child("uid").setValue(uid);
// mRef.child(name).setValue(user);
Log.d(TAG, uid);
Intent intent = new Intent(getApplicationContext(), CustomColorActivity.class);
intent.putExtra("user_id",uid);
intent.putExtra("profile_picture",image);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
MainFragment.java
public class MainFragment extends Fragment {
private static final String TAG = "AndroidBash";
public User user;
private Firebase myFirebaseRef =new Firebase("https://fitmaker-ee2c0.firebaseio.com/");
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private TextView name;
private TextView welcomeText;
private Button changeButton;
private Button revertButton;
private Button FBButton;
private ProgressDialog mProgressDialog;
// To hold Facebook profile picture
private ImageView profilePicture;
public MainFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container,
false);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
//((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
//Add YOUR Firebase Reference URL instead of the following URL
myFirebaseRef = new Firebase("https://fitmaker-ee2c0.firebaseio.com/");
mAuth = FirebaseAuth.getInstance();
name = (TextView) view.findViewById(R.id.text_view_name);
welcomeText = (TextView) view.findViewById(R.id.text_view_welcome);
changeButton = (Button) view.findViewById(R.id.button_change);
revertButton = (Button) view.findViewById(R.id.button_revert);
FBButton = (Button) view.findViewById(R.id.button_fb);
profilePicture = (ImageView) view.findViewById(R.id.profile_picture);
//Get the uid for the currently logged in User from intent data passed to this activity
String uid = getActivity().getIntent().getExtras().getString("user_id");
//Get the imageUrl for the currently logged in User from intent data passed to this activity
String imageUrl = getActivity().getIntent().getExtras().getString("profile_picture");
Log.d(TAG, "MainFrag - OnCreateView Check");
new ImageLoadTask(imageUrl, profilePicture).execute();
//Referring to the name of the User who has logged in currently and adding a valueChangeListener
myFirebaseRef.child(uid).child("name").addValueEventListener(new ValueEventListener() {
//onDataChange is called every time the name of the User changes in your Firebase Database
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Inside onDataChange we can get the data as an Object from the dataSnapshot
//getValue returns an Object. We can specify the type by passing the type expected as a parameter
String data = dataSnapshot.getValue(String.class);
name.setText("Hello " + data + ", ");
}
//onCancelled is called in case of any error
@Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getActivity().getApplicationContext(), "" + firebaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
//A firebase reference to the welcomeText can be created in following ways :
// You can use this :
//Firebase myAnotherFirebaseRefForWelcomeText=new Firebase("https://androidbashfirebaseupdat-bd094.firebaseio.com/welcomeText");*/
//OR as shown below
myFirebaseRef.child("welcomeText").addValueEventListener(new ValueEventListener() {
//onDataChange is called every time the data changes in your Firebase Database
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Inside onDataChange we can get the data as an Object from the dataSnapshot
//getValue returns an Object. We can specify the type by passing the type expected as a parameter
String data = dataSnapshot.getValue(String.class);
welcomeText.setText(data);
}
//onCancelled is called in case of any error
@Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getActivity().getApplicationContext(), "" + firebaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
//onClicking changeButton the value of the welcomeText in the Firebase database gets changed
changeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myFirebaseRef.child("welcomeText").setValue("Android App Development @ AndroidBash");
}
});
FBButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// log user out
// add choice dialog later
LogOut();
}
});
//onClicking revertButton the value of the welcomeText in the Firebase database gets changed
revertButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myFirebaseRef.child("welcomeText").setValue("Welcome to Learning @ AndroidBash");
}
});
return view;
}
@Override
public void onResume() {
Log.d(TAG, "onResume of MainFragment");
CheckIfLoggedOut();;
super.onResume();
}
public void CheckIfLoggedOut() {
// here, check if user still logged in.
FirebaseUser mUser = mAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Log.d(TAG, "MainFrag - Signed In (onResume)");
} else {
// User is signed out
Log.d(TAG, "check resume: starting log out for " + mUser.getUid());
LogOut();
}
}
public void LogOut(){
Log.d(TAG, "CHECK #2: USER SIGNED OUT");
getActivity().getIntent().removeExtra("user_id");
getActivity().getIntent().removeExtra("profile_picture");
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
Log.d(TAG, "signed out" + mUser.getUid());
// mAuth.unauth();
Intent intent = new Intent(getActivity().getApplicationContext(),
LoginActivity.class);
myFirebaseRef.unauth();
LoginManager.getInstance().logOut();
startActivity(intent);
Log.d(TAG, "CHECK 3: FINISIHED SIGNED OUT");
Log.d(TAG, "onAuthStateChanged:signed_out");
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(getContext());
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
答案 0 :(得分:1)
FirebaseAuth.getInstance().signOut();
添加这条线解决了我的问题。