I'm doing Sign In with Google+ that leads to the Navigation.activity. Ive follow the instruction on Google developer but I only took signIn method(Success) but now im stuck at navigation.activity. How do i make logout from navigationItemSelected?
What is the problem :
Google plus signIn in Main Activity but need to Logout from Navigation Activity...
TY for helping
else if (id == R.id.logout) {
}
This is my onResult
#Override
public void onResult(GoogleSignInResult googleSignInResult) {
hideProgressDialog();
handleSignInResult(googleSignInResult);
}
It will call hideprogress and handleSignInResult method..
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
Intent intent = new Intent(Main.this,HomeActivity.class);
startActivity(intent);
} else {
// Signed out
}
}
private void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.hide();
}
}
You can visit Signing Out Users and Disconnecting Accounts official link to perform SignOut and Revoke Access operation
Singout
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
// ...
}
});
}
Disconnect account
private void revokeAccess() {
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
// ...
}
});
}
Related
i'm now making android apps, so here is my VerifyOTP class , I'm getting E/zzbf: SafetyNet Attestation fails basic integrity. error ...
Can Someone please help me .
this SafetyNet I just can't understand...
I've tried everything, the aplication should automatically entered Code given by SMS ... but when I enter my information in aplication, my phone number is passed by Intent ... end used in sendVerificationCodeToUser()...
public class VerifyOTP extends AppCompatActivity {
// Variables
PinView pinFromUser;
ImageView closeBtn;
String codeBySystem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_verify_o_t_p);
// Hooks
pinFromUser = findViewById(R.id.pin_view);
closeBtn = findViewById(R.id.otp_close_btn);
String _phoneNo = getIntent().getStringExtra("phone");
sendVerificationCodeToUser(_phoneNo);
closeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VerifyOTP.super.onBackPressed();
}
});
}
private void sendVerificationCodeToUser(String phone) {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber(phone) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks =
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
codeBySystem = s;
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
pinFromUser.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(VerifyOTP.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
};
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codeBySystem, code);
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(VerifyOTP.this, "Verification Completed!", Toast.LENGTH_SHORT).show();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(VerifyOTP.this, "Verification failed!", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void CallNextFromOTP(View view) {
String code = pinFromUser.getText().toString();
if (!code.isEmpty()) {
verifyCode(code);
}
}
}
did you add at AndroidManifest.xml these permissions ?
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
i think because your code is missing premission check function that's why send you to navigation add this code to your code in VerifyOTP.java
private void checkForSmsPermission() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS) !=
PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, getString(R.string.permission_not_granted));
// Permission not yet granted. Use requestPermissions().
// MY_PERMISSIONS_REQUEST_SEND_SMS is an
// app-defined int constant. The callback method gets the
// result of the request.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
} else {
// Permission already granted. Enable the SMS button.
enableSmsButton();
}
}
Add these dependencies in your build.gradle :
implementation "androidx.browser:browser:1.3.0"
implementation "com.google.firebase:firebase-messaging:21.1.0"
Firebase Quote "The reCAPTCHA flow will only be triggered when SafetyNet is unavailable or your device does not pass suspicion checks. Nonetheless, you should ensure that both scenarios are working correctly." So to enable SafetyNet, follow the below steps or you can also visit Firebase Auth for more info.
Go to google cloud console, select your project.
Click on the navigation menu and select APis & services and then select Dashboard.
Click on enable api and services and enable api " Android Device Verification".
Add SHA 256 in firebase project settings.(debug and release both)
Download and replace the latest google-services.json file in your project.
I am facing an issue with retrofit login. when i run the application in my cell phone , i logged in with a registered user... login successful... but when i logged out and want to re-login with another account the "application logged me in with the previous account" ... i am not understanding what is this issue please help.
i am not understanding why this issue is occurring with my application.
Note: i am using retrofit (with Firebase) in the application for signup and login.
Thanks
here is the code of my Login Class
private Button forgot ;
private TextView CreactAccount_text;
private EditText login_email , login_password;
private ProgressDialog mLoginProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
Toolbar toolbar = (Toolbar) findViewById(R.id.login_page_toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar()!= null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
FirebaseApp.initializeApp(this);
// Realm.init(this);
// User Session Manager
Window window = getWindow();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
window.setStatusBarColor(getColor(R.color.login_statusbar_color));
}
else {
window.setStatusBarColor(getResources().getColor(R.color.login_statusbar_color));
}
mLoginProgress = new ProgressDialog(this);
CreactAccount_text = (TextView) findViewById(R.id.ui_crateaccount_text);
forgot = (Button) findViewById(R.id.ui_btn_forgot);
forgot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent forgot_password = new Intent(Login_Activity.this , Forgot_Password_Activity.class);
startActivity(forgot_password);
}
});
CreactAccount_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent move_signup = new Intent(Login_Activity.this , Signup_Activity.class);
startActivity(move_signup);
}
});
login_email = (EditText) findViewById(R.id.ui_login_email);
login_password = (EditText) findViewById(R.id.ui_login_password);
findViewById(R.id.ui_signin).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usersignin();
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(
R.anim.no_anim, R.anim.slide_right_out);
AppUtils.hideSoftKeyboard(this);
}
public void usersignin(){
final String email = login_email.getText().toString().trim();
final String password = login_password.getText().toString().trim();
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
login_email.setError("Email is not correctly formated");
login_email.requestFocus();
return;
}
if (password.isEmpty()){
login_password.setError("password is required");
login_password.requestFocus();
return;
}
if (password.length() < 6){
login_password.setError("Password should be atleast 6 characters");
login_password.requestFocus();
return;
}
if(!TextUtils.isEmpty(email) || !TextUtils.isEmpty(password)){
mLoginProgress.setTitle("Logging In");
mLoginProgress.setMessage("Please wait while we check your credentials.");
mLoginProgress.setCanceledOnTouchOutside(false);
mLoginProgress.show();
SharedPreferenceUtil.storeStringValue(Login_Activity.this, Constants.USERNAME,email);
SharedPreferenceUtil.storeStringValue(Login_Activity.this,Constants.PASSWORD,password);
RetrofitUtil.createProviderAPI().userLogin(email , password).enqueue(loginUser(this));
}
}
#Override
public void onLoginUser(RetrofitClientLogin data) {
if(data.getType().equals(Constants.SUCCESS)){
FirebaseInstanceId.getInstance().getToken();
UtilFirebaseAnalytics.logEvent(Constants.EVENT_LOGIN,Constants.KEY_EMAIL,login_email.getText().toString());
SharedPreferenceUtil.storeBooleanValue(this,Constants.ISUSERLOGGEDIN,true);
if(getIntent() != null && getIntent().getBooleanExtra(Constants.IS_RESULT_ACTIVITY,false)){
setResult(RESULT_OK);
}else{
hideProgressDialog();
openAcitivty(Home_Activity.class);
}
loginOnFirebase();
}
}
private void loginOnFirebase(){
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
final String email = login_email.getText().toString();
final String password = login_password.getText().toString();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(Login_Activity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
hideProgressDialog();
finish();
}
});
}else{
hideProgressDialog();
finish();
}
}
});
}
}
protected void openAcitivty(Class<?> cls) {
Intent intent = new Intent(this, cls);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
protected void showProgressDialog(String msg) {
try {
if (mLoginProgress != null && !mLoginProgress.isShowing()) {
mLoginProgress.setMessage(msg);
mLoginProgress.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void hideProgressDialog() {
try {
if (mLoginProgress != null && mLoginProgress.isShowing()) {
mLoginProgress.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSignup(RetrofitClientLogin data) {
}
#Override
public void OnError(String error) {
hideProgressDialog();
Toast.makeText(this,error,Toast.LENGTH_LONG).show();
}
You're using SharedPreferences for storing login credentials. Once user enters valid login credentials (login ID and password) you store it in SharedPreferences in usersignin() method.
SharedPreferenceUtil.storeStringValue(Login_Activity.this, Constants.USERNAME, email);
SharedPreferenceUtil.storeStringValue(Login_Activity.this, Constants.PASSWORD, password);
Now, I am assuming (you only posted LoginActivity and didn't mention other parts) that your app has Splash page. Which appears before Login page. In which you decide whether the user has already logged in or not (using SharedPreference values). If yes, redirect to Home page else Login page.
The fix for this issue is very simple. When user logs out from the app, you need to clear SharedPreferences as well.
Like this,
SharedPreferenceUtil.storeStringValue(Login_Activity.this, Constants.USERNAME, null);
SharedPreferenceUtil.storeStringValue(Login_Activity.this, Constants.PASSWORD, null);
I am using Firebase to sign in the user and have implemented the code to exit the app on double click. But the problem is the same screen is popping up again.
I tried a workaround setting a SharedPreference and then checking that in mAuthListner. But it did not work.
Here are the relevant sections of the code:
mAuthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
SharedPreferences d= getSharedPreferences("backPressed", Context.MODE_PRIVATE);
Boolean t = d.getBoolean("back",false);
if (firebaseAuth.getCurrentUser() != null && !t) {
startActivity(new Intent(MainActivity.this, Second.class));
}
if (t) {
d.edit().putBoolean("back",false);
}
}
};
Code for back button pressed:
boolean doubleBackToExitPressedOnce = false;
private Handler mHandler = new Handler();
private final Runnable mRunnable = new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
};
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
SharedPreferences d= getSharedPreferences("backPressed",Context.MODE_PRIVATE);
d.edit().putBoolean("back",true);
finish();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
mHandler.postDelayed(mRunnable, 2000);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mHandler != null) { mHandler.removeCallbacks(mRunnable); }
}
How can I exit the app on back pressed twice while keeping the user logged in?
This is not a Firebase issue as Firebase will not log out until you specifically call the "Log Out" method.
You do not need SharedPreferences. Just set an Activity level variable BackOnce to False then set it in the OnBackPressed as necessary.
boolean BackOnce = false;
#Override
public void onBackPressed() {
if (BackOnce) {
finish();
} else {
BackOnce = true;
Snackbar sb = Snackbar.make(myView, "Press back again to close app", Snackbar.LENGTH_SHORT);
sb.addCallback(new Snackbar.Callback() {
#Override
public void onDismissed(Snackbar snackbar, int event) {
super.onDismissed(snackbar, event);
BackOnce = false;
}
});
sb.show();
}
}
I'm trying to sign out of google but I'm getting the error
IllegalStateException Google API Client is not connected yet.
#Override
public void onClick(View v) {
signOut();
}
}
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
tv_username.setText("");
}
});
}
I have made an app in that I want to share an image and a text ,I have successfully get the login Dialog of facebook..But after Login it gives me error that Warning: Sessionless Request needs token but missing either application ID or client token.
What should i do to solve it.My code is as below ,Please help needed..
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
Session session = facebook.getSession();
if (access_token != null) {
SessionState st = SessionState.OPENED;
facebook.setAccessToken(access_token);
Exception e = new FacebookError("Error");
System.out.println("::::::::::::::aCEESS TOKEN::::::::;;"
+ access_token);
postToWall();
/*fbImageSubmit(facebook, big_img, "3sMAniquines", "Maniquines",
cat_nem, big_img);*/
onSessionStateChange(session, st, e);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (facebook.isSessionValid()) {
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
* */
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
You have to save the access token of logged user for maintaining Session for further task.
according to your code following code will give you currently logged in user's access token.
String access_token = Const.fb.getAccessToken();