how to log out Google Play Game? - java

I can log in to Google Play Games, but I can't log out.I get the following error.
GoogleApiClient is not configured to use the Plus.API api.
Here my codes;
public void Glogin(View view) {
//HERE LOGIN
if (loginout==0)
{
apiClient = new GoogleApiClient.Builder(this)
.addApi(Games.API)
.addScope(Games.SCOPE_GAMES)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.e("HATA", "Google Play Oyun servisine bağlanamadı.Lütfen bağlantınızı kontrol ediniz.");
finish();
}
}).build();
btn_gLoginout.setBackgroundResource(R.drawable.logout);
loginout++;
}
//LOGOUT
else if(loginout==1){
if (apiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(apiClient);
apiClient.disconnect();
apiClient.connect();
Toast.makeText(this, "Google hesabınızdan çıkış yapıldı.", Toast.LENGTH_SHORT).show();
btn_gLoginout.setBackgroundResource(R.drawable.login);
loginout=0;
}
}
}

Related

Can't implement SMS Verification into my android app

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.

Connecting fail when connect to the Google Api Client

I try connecting to the Google API Client to achieve some functionality in my application. But for some reason I cannot connect to the Google API Client And because that I can not continue to use Google services.
After I initialize the GoogleApiClient I check if mGoogleApiClient.isConnected and always get it False and I don't know why. I would appreciate any help. Thanks.
Notice that everything happens on background service.
public class Background extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<Status> {
private String TAG = "Background";
private GoogleApiClient mGoogleApiClient;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG,"Start");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(ActivityRecognition.API)
.addApi(LocationServices.API)
.build();
if (!mGoogleApiClient.isConnected()) {
Log.e(TAG,"GoogleApiClient not yet connected");
} else {
Log.e(TAG,"GoogleApiClient connected");
}
return Service.START_STICKY;
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.e(TAG, "Successfully added activity detection.");
} else {
Log.e(TAG, "Error: " + status.getStatusMessage());
}
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected");
mGoogleApiClient.connect();
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
Connect the googleApiClient in onStartCommand of your service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG,"Start");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(ActivityRecognition.API)
.addApi(LocationServices.API)
.build();
if (!mGoogleApiClient.isConnected()) {
Log.e(TAG,"GoogleApiClient not yet connected");
mGoogleApiClient.connect(); // connect it here..
} else {
Log.e(TAG,"GoogleApiClient connected");
}
return Service.START_STICKY;
}
you are not calling .connect() in the right place. You are building a client, and you must call .connect() after that. You are immediately checking if it is connected, which it will never be.
Please add .connect() after .build() in .onStartCommand() and remove this code:
if (!mGoogleApiClient.isConnected()) {
Log.e(TAG,"GoogleApiClient not yet connected");
} else {
Log.e(TAG,"GoogleApiClient connected");
}
Also, remove this since it might get you in an unwanted state:
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected");
// remove this -> mGoogleApiClient.connect();
}

Android FireBase - Connect to Game Service Leaderboard

I have made a login activity using firebase to connect with google. The user can login without problems Now I want to show a leaderboard on another activity however, when I check if the user is logged in and I try to show the leaderboard I get the error:
E/UncaughtException: java.lang.IllegalStateException: GoogleApiClient
must be connected.
How can I connect GoogleApiClient using firebase? I have tried using mGoogleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL); but this also does not work.
here my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_achievements);
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
// connection failed, should be handled
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
////// is crashing googleapiclient not connected
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mGoogleApiClient,
getString(R.string.leaderboard_la_classifica)), REQUEST_LEADERBOARD);
} else {
// User is signed out
}
// ...
}
};
}
See https://firebase.google.com/docs/auth/android/google-signin for more details.
When building the client, you need to use GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_firebase_games_signin);
String webclientId = getString(R.string.web_client_id);
GoogleSignInOptions options =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
.requestServerAuthCode(webclientId)
.requestEmail()
.requestIdToken()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
.addApi(Auth.GOOGLE_SIGN_IN_API, options)
.addConnectionCallbacks(this)
.build();
}
Then to start the explicit sign-in start the signIn Intent:
private void signIn() {
Intent signInIntent =
Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
You should also use an automanaged client, or simply call mGoogleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL); in onStart() and disconnect in onStop().
In onActivityResult, handle the result of the explicit sign-in intent:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.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 acct = result.getSignInAccount();
completeFirebaseAuth(acct);
// At this point, the Games API can be called.
} else {
// Google Sign In failed, update UI appropriately
// ...
}
}
}
Completing the Firebase authentication:
private void completeFirebaseAuth(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
FirebaseAuth mAuth = FirebaseAuth.getInstance();
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());
}
// ...
}
});
}
The other situation you need to handle is the silent sign-in, which happens when resuming an app:
#Override
public void onConnected(#Nullable Bundle bundle) {
// Handle the silent sign-in case.
if (mGoogleApiClient.hasConnectedApi(Games.API)) {
Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient).setResultCallback(
new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(
#NonNull GoogleSignInResult googleSignInResult) {
if (googleSignInResult.isSuccess()) {
completePlayGamesAuth(
googleSignInResult.getSignInAccount());
} else {
Log.e(TAG, "Error with silentSignIn: " +
googleSignInResult.getStatus());
}
}
}
);
}
}

When I try to signout from GoogleApiClient I got Error message GoogleApiClient.isConnected() on a null object reference

When I try to sign out from GoogleApiClient I got the following error message
GoogleApiClient.isConnected() on a null object reference
Here is my code:
public static GoogleSignInOptions gso;
public static GoogleApiClient mGoogleApiClient;
//.........
google.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
mGoogleApiClient = new GoogleApiClient.Builder(getContext()).enableAutoManage(getActivity(), new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(getContext(), "Login failed", Toast.LENGTH_LONG).show();
}
}).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
Intent intent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(intent, requestCode);
mGoogleApiClient.connect();
Toast.makeText(getContext(),"User Name "+ acc.getDisplayName()+ "Mail "+acc.getEmail(), Toast.LENGTH_LONG).show();
}
});
and my sign out code
public void signout(){
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
Intent intent1 = new Intent(getContext(),LoginActivity.class);
startActivity(intent1);
getActivity().finish();
}
});
And I also tried:
if (UserLogin.mGoogleApiClient.isConnected()) {
UserLogin.mGoogleApiClient.disconnect();
}
Try this...
Define:
public GoogleSignInOptions gso;
public GoogleApiClient mGoogleApiClient;
Initialize in Oncreate method:
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
mGoogleApiClient.connect();
Now set click listener on signIn button
google.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(intent, requestCode);
Toast.makeText(getContext(),"User Name "+ acc.getDisplayName()+ "Mail "+acc.getEmail(), Toast.LENGTH_LONG).show();
}
});
/////
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(getContext(), "Login failed", Toast.LENGTH_LONG).show();
}
//Sign out
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
Intent intent1 = new Intent(getContext(),LoginActivity.class);
startActivity(intent1);
getActivity().finish();
}
});
}
Hope this will help you.

FusedLocationProviderAPI always returns null when trying to get current location

For countless hours, I have been trying to get the user's current location upon launching my app, but then every approach I have tried has returned null.
My instantiation of the GoogleApiClient takes place in "onCreate"
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
FirebaseMessagingHelper.registerDevice(this, FirebaseInstanceId.getInstance().getToken());
activity = this;
//xaxaxa
driverMapView = (MapView) findViewById(R.id.googleMapObject);
driverMapView.onCreate(savedInstanceState);
driverMapView.getMapAsync(this);
getUserToEnableCameraUsage();
if (googleApiClient == null)
{
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
googleApiClient.connect();
Here is the code in my project (extremely similar to the code provided in the api's tutorial:
#Override
public void onConnected(#Nullable Bundle bundle)
{
int LOCATION_ALLOWED = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
if (LOCATION_ALLOWED != PackageManager.PERMISSION_GRANTED)
{
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null)
{
driverGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()), 16));
testHelper.setDriverLatLngLocation(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()));
}
}
}
protected void createLocationRequest()
{
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(500);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder locationSettingsRequestBuilder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
PendingResult<LocationSettingsResult> pendingResult = LocationServices
.SettingsApi
.checkLocationSettings(googleApiClient, locationSettingsRequestBuilder.build());
pendingResult.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult locationSettingsResult)
{
Status result = locationSettingsResult.getStatus();
if (result.getStatusCode() == LocationSettingsStatusCodes.SUCCESS)
{
requestingLocationUpdates = true;
startLocationUpdates();
Toast.makeText(MainActivity.this, "Gucci", Toast.LENGTH_SHORT).show();
}
if (result.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED)
{
requestingLocationUpdates = false;
Toast.makeText(MainActivity.this, "Please enable location services", Toast.LENGTH_SHORT).show();
}
if (result.getStatusCode() == LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE)
{
requestingLocationUpdates = false;
Toast.makeText(MainActivity.this, "App cannot access settings", Toast.LENGTH_SHORT).show();
}
}
});
}
protected void startLocationUpdates()
{
int LOCATION_ALLOWED = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
if (LOCATION_ALLOWED != PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
}
#Override
public void onLocationChanged(Location location)
{
driverGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 16));
testHelper.setDriverLatLngLocation(new LatLng(location.getLatitude(), location.getLongitude()));
Toast.makeText(MainActivity.this, "It's working", Toast.LENGTH_SHORT).show();
}
protected void stopLocationUpdates()
{
LocationServices.FusedLocationApi.removeLocationUpdates(
googleApiClient, this);
requestingLocationUpdates = false;
}
I instantiate "createLocationRequest here:
public void onMapReady(GoogleMap googleMap)
{
//Setting map starts here
int LOCATION_ALLOWED = ContextCompat.checkSelfPermission(this.getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
if (LOCATION_ALLOWED == PackageManager.PERMISSION_GRANTED)
{
googleMap.setMyLocationEnabled(true);
}
createLocationRequest();
The instantiation of "createLocationRequest()" takes place before the block of code that needs it and it is null?
I have looked over multiple solutions, but they've all not helped me. I was hoping that maybe someone could help me out as this has been really bothering me and has halted the development of my app.

Categories

Resources