Unable to integrate google sign in properly in android app - android

I wanted to add the sign in with google feature of firebase I connected my app to firebase then added the SHA-1 certificate fingerprint and wrote the below code.
Once I click on the sign in button the intent opens a chooser to select a google account but after selecting one account nothing happens even there is no exceptions or error in the logcat.
Code:
class SignInActivity : AppCompatActivity() {
private lateinit var googleSignInClient:GoogleSignInClient
private lateinit var auth:FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_in)
val gso= GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this,gso)
signInButton.setOnClickListener {
resultLauncher.launch(googleSignInClient.signInIntent)
}
}
private var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
val intent=it.data
if(it.resultCode == Activity.RESULT_OK)
{
val task = GoogleSignIn.getSignedInAccountFromIntent(intent)
handleSignInResult(task)
}
}
private fun handleSignInResult(task: Task<GoogleSignInAccount>?) {
try{
val account= task?.getResult(ApiException::class.java)!!
Log.i("account","firebaseAuthWithGoogle:"+account.id)
firebaseAuthWithGoogle(account.idToken!!)
}catch (e : ApiException){
Log.i(TAG, "Google sign in failed", e)
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
signInButton.visibility= View.GONE
progressBar.visibility=View.VISIBLE
val credential=GoogleAuthProvider.getCredential(idToken,null)
GlobalScope.launch(Dispatchers.IO) {
val auth=auth.signInWithCredential(credential).await()
val firebaseUser=auth.user
Log.i("user",firebaseUser.toString())
withContext(Dispatchers.Main){
updateUI(firebaseUser)
}
}
}
private fun updateUI(firebaseUser: FirebaseUser?) {
if(firebaseUser != null)
{
val intent=Intent(this,MainActivity::class.java)
startActivity(intent)
Log.i("intent","Intent Started")
// Toast.makeText(applicationContext,"Sign In Successful",Toast.LENGTH_SHORT).show()
finish()
}
else{
signInButton.visibility= View.VISIBLE
progressBar.visibility=View.GONE
Toast.makeText(this,"Sign In failed",Toast.LENGTH_SHORT).show()
}
}
}
Logcat:
I am very new to android development and this is my first time with firebase.

Related

How to get step count with GoogleFit Api Sensor Manager

I am trying to geth step count and heart rpm from the Google Fit Api. I am aware that the getHistoryClient and getSensorClient are deprecated.
Please how can I replace this methods with the Sensor Manager. I do not seem to undersatnd the documentation.
class MainActivity : AppCompatActivity(), SensorEventListener {
private val listOfPermissionNotGranted = mutableListOf<String>()
lateinit var permissionsLauncher: ActivityResultLauncher<Array<String>>
lateinit var signInLauncher: ActivityResultLauncher<Intent>
private val sensorManager: SensorManager by lazy { getSystemService(SENSOR_SERVICE) as SensorManager }
private val accelerometer by lazy { sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) }
lateinit var googleApiClient: GoogleSignInClient
#RequiresApi(Build.VERSION_CODES.Q)
#OptIn(ExperimentalTime::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
signInLauncher = registerForActivityResult(StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
if (task.isSuccessful) {
Toast.makeText(this, "Signed in", Toast.LENGTH_LONG).show()
Log.d("MainUser", "${task.result}")
val fitnessOptions = FitnessOptions.builder()
.addDataType(DataType.TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ)
.addDataType(
DataType.AGGREGATE_STEP_COUNT_DELTA,
FitnessOptions.ACCESS_READ
)
.build()
Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
.readDailyTotal(DataType.TYPE_STEP_COUNT_DELTA)
.addOnSuccessListener { result ->
val totalSteps =
result.dataPoints.firstOrNull()?.getValue(Field.FIELD_STEPS)?.asInt() ?: 0
// Do something with totalSteps
Log.i("Main", "total $totalSteps")
}
.addOnFailureListener { e ->
Log.i("Main", "There was a problem getting steps.", e)
}
// val googleSignInAccount =
// GoogleSignIn.getAccountForExtension(this, fitnessOptions)
}
}
}
permissionsLauncher = registerForActivityResult(RequestMultiplePermissions()) { permissionMap ->
val permitted = permissionMap.all { it.value }
if (permitted) {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Fitness.SCOPE_ACTIVITY_READ)
.build()
googleApiClient = GoogleSignIn.getClient(this, gso)
val signInIntent = googleApiClient.signInIntent
signInLauncher.launch(signInIntent)
}
}
permissionsLauncher.launch(
arrayOf(
Manifest.permission.BODY_SENSORS,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACTIVITY_RECOGNITION
)
)
listOfPermissionNotGranted.forEach { permission ->
Toast.makeText(this, "$permission is not granted", Toast.LENGTH_LONG).show()
}
}
override fun onResume() {
super.onResume()
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL)
}
override fun onPause() {
super.onPause()
sensorManager.unregisterListener(this)
}
override fun onSensorChanged(event: SensorEvent?) {
if (event?.sensor?.type == Sensor.TYPE_STEP_DETECTOR) {
Log.d("MainSensorStep detected", "${event.values[0]}")
Toast.makeText(this, "Step is detected ${event.values[0]}", Toast.LENGTH_LONG).show()
} else if (event?.sensor?.type == Sensor.TYPE_STEP_COUNTER) {
Log.d("MainSensorStep counting", "${event.values[0]}")
Toast.makeText(this, "Step is counting ${event.values[0]}", Toast.LENGTH_LONG).show()
}
}
override fun onAccuracyChanged(sensor: Sensor?, p1: Int) {
Log.d("MainSensor", "$sensor")
}
}
You might want to go over this answer in a separate, but related SO post, and get a better understanding of the different approaches.
If you need to collate processed steps information from the User, then Google Fit is the better approach. You can see how you get the same step count as what's on the google fit app using the cited example code in their official docs: https://developers.google.com/fit/scenarios/read-daily-step-total#android
I see that you're also using the Android API for Fit, you might want to explore Android Health Connect too as the Android API for Fit will be deprecated soon.

android - Firebase phone authentication recaptch

I'm working on an android app which require Firebase phone authentication, When I released my app, a recapture still required as in debug mode, I enabled Android Device Verification in google cloud console, also I added google play console SHA-256, SHA-1 to Firebase project setting.
Bellow my Kotlin code of Firebase authentication:
fun initFirebase() {
mAuth = FirebaseAuth.getInstance()
}
fun sendOtp(mobile: String, resend: Boolean) {
if (resend) resend(mobile)
else send(mobile)
}
private fun send(mobile: String) {
val options = PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber(mobile)
.setTimeout(5L, TimeUnit.SECONDS)
.setActivity(requireActivity())
.setCallbacks(mCallbacks)
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
}
Also at many time I get VerificationFailed without getting reason of this failure
private val mCallbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(authCredential: PhoneAuthCredential) {}
override fun onVerificationFailed(e: FirebaseException) {
events.value = Constant.EVENT_SEND_FAILED
Log.v("TAG","VerificationFailed")
}
override fun onCodeSent(
verificationId: String,
forceResendingToken: PhoneAuthProvider.ForceResendingToken
) {
Log.v("TAG","Success")
}
and in verification fragment:
private lateinit var mAuth: FirebaseAuth
var mVerificationId: String = ""
fun verifyOtp(otp: String) {
val credential = PhoneAuthProvider.getCredential(
mVerificationId,
otp
)
mAuth.signInWithCredential(credential).addOnCompleteListener(requireActivity()) {
if (it.isSuccessful) {
mAuth.currentUser?.getIdToken(true)?.addOnCompleteListener { task ->
if (task.isSuccessful && task.result != null) {
val phoneVerificationToken = task.result.token
if (phoneVerificationToken != null) {
Log.v("TAG","Success")
}
} else {
Log.v("TAG","Error")
}
}
} else {
Log.v("TAG","Invalid code")
}
}
}

google authentication pop up not working using firebase in android development

while doing a project...i did an authentication with a google account. but it's not working
MainActivity.kt in this activity I have implemented authentication uisng firebase but when i click the button no popup is showing
class MainActivity : AppCompatActivity() {
private lateinit var mAuth: FirebaseAuth
private lateinit var googleSignInClient: GoogleSignInClient
private lateinit var binding: ActivityMainBinding
companion object{
private const val RC_SIGN_IN = 120
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(R.layout.activity_main)
// Configure Google Sign In
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this, gso)
mAuth = FirebaseAuth.getInstance()
binding.gbutton.setOnClickListener{
signIn()
}
}
private fun signIn() {
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
val exception = task.exception
if(task.isSuccessful){
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)!!
Log.d("SignInActivity", "firebaseAuthWithGoogle:" + account.id)
firebaseAuthWithGoogle(account.idToken!!)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w("SignInActivity", "Google sign in failed", e)
}
}
else{
Log.w("SignInActivity", exception.toString())
}
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d("SignInActivity", "signInWithCredential:success")
val intent = Intent(this,ActivityGoogleSigninBinding::class.java)
startActivity(intent)
finish()
} else {
// If sign in fails, display a message to the user.
Log.d("SignInActivity", "signInWithCredential:failure", task.exception)
}
}
}
}
Gradle scripts and buttonID (using binding, XML file in layout) are done correctly
I have also checked logcat but couldn't found any error
Please help

firebase google sign in result code is always 0

I wanted to integrate google sign In in my app using firebase and I followed all the instructions from enabling google sign In in my firebase console and adding SHA-1 certificate fingerprint and adding the google-services.json file in the app directory.
But whenever I am trying to sign In after selecting the google account the response code is coming out be 0 always and hence unable to sign In.
Here is the Code:-
class SignInActivity : AppCompatActivity() {
private lateinit var googleSignInClient: GoogleSignInClient
private lateinit var auth:FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_in)
val gso= GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this,gso)
signInButton.setOnClickListener {
resultLauncher.launch(googleSignInClient.signInIntent)
}
}
private var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){result->
Log.i("resultCode",result.resultCode.toString())
val intent=result.data
Log.i("intentData",intent.toString())
if(result.resultCode == Activity.RESULT_OK)
{
Log.i("resultCode","reachedHere")
val task = GoogleSignIn.getSignedInAccountFromIntent(intent)
handleSignInResult(task)
}
else{
Log.i("unsuccessfulSignIN",result.resultCode.toString())
}
}
private fun handleSignInResult(task: Task<GoogleSignInAccount>?) {
try{
val account= task?.getResult(ApiException::class.java)!!
Log.i("account","firebaseAuthWithGoogle:"+account.id)
firebaseAuthWithGoogle(account.idToken!!)
}catch (e : ApiException){
Log.i(ContentValues.TAG, "Google sign in failed", e)
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
signInButton.visibility= View.GONE
progressBar.visibility= View.VISIBLE
val credential= GoogleAuthProvider.getCredential(idToken,null)
GlobalScope.launch(Dispatchers.IO) {
val auth=auth.signInWithCredential(credential).await()
val firebaseUser=auth.user
Log.i("user",firebaseUser.toString())
withContext(Dispatchers.Main){
updateUI(firebaseUser)
}
}
}
private fun updateUI(firebaseUser: FirebaseUser?) {
if(firebaseUser != null)
{
val intent= Intent(this,MainActivity::class.java)
startActivity(intent)
Log.i("intent","Intent Started")
// Toast.makeText(applicationContext,"Sign In Successful",Toast.LENGTH_SHORT).show()
finish()
}
else{
signInButton.visibility= View.VISIBLE
progressBar.visibility=View.GONE
Toast.makeText(this,"Sign In failed", Toast.LENGTH_SHORT).show()
}
}
}
Here is the logcat ( I have highlighted the result code that I logged)
I am very new to android development and this my first time working with firebase

Login with google work from android studio but don't work from google play

I built an app with google login.
When I connect the device to the android studio the log in work perfect, But when I download my app from google play it fails to connect for some reason...
I tried to find a solution and I couldn't find one...
That's the code ... I would love if anyone has any idea what the problem is..
Thanks for your time!
class firstActivity : AppCompatActivity(){
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
auth = FirebaseAuth.getInstance()
val acct = GoogleSignIn.getLastSignedInAccount(this)
if (acct != null) {
val personName = acct.displayName
val personGivenName = acct.givenName
val personFamilyName = acct.familyName
val personEmail = acct.email
val personId = acct.id
}
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_idd))
.requestEmail()
.build()
val mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signinButtonGoogle.setOnClickListener {
val signInIntent: Intent = mGoogleSignInClient.getSignInIntent()
startActivityForResult(signInIntent, Companion.RC_SIGN_IN)
}
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
GoogleSignInApi.getSignInIntent(...);
if (requestCode == Companion.RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
val account = task.getResult(ApiException::class.java)
firebaseAuthWithGoogle(account!!)
} catch (e: ApiException) {
Toast.makeText(applicationContext, "Google sign in failed", Toast.LENGTH_SHORT)
.show()
}
}
}
private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) {
val progressDialog = ProgressDialog(this)
progressDialog.setMessage("Connecting...")
progressDialog.setCancelable(false)
progressDialog.show()
val credential = GoogleAuthProvider.getCredential(acct.idToken, null)
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val user = auth.currentUser
signinButtonGoogle.visibility = View.VISIBLE
Handler().postDelayed({ progressDialog.dismiss() }, 0)
val leagueIntent = Intent(this, homeActivity::class.java)
startActivity(leagueIntent)
} else {
Toast.makeText(applicationContext, "Authentication Failed.", Toast.LENGTH_SHORT).show()
signinButtonGoogle.visibility = View.VISIBLE
Handler().postDelayed({ progressDialog.dismiss() }, 0)
}
}
}
companion object {
const val RC_SIGN_IN = 123
}
}
because google play have another SH1 for relase , so you can find it like image and goto firbase manger for your prokect then add new one ,
image

Categories

Resources