I am able to upload to google drive using accounts added in Android phone .I followed steps as told in http://www.youtube.com/watch?v=Ied1CjJ0iP0 . What i actually want to do is to upload to a single account from multiple phones via a service as a background process .How can i do it .
I did this by first logging in using the normal method from my fragment
private fun upload() {
Log.i(TAG, "Start sign in")
val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.build()
val googleSignInClient = GoogleSignIn.getClient(this.requireActivity(), signInOptions)
startActivityForResult(googleSignInClient.signInIntent, MyFragment.REQUEST_CODE_SIGN_IN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
MyFragment.REQUEST_CODE_SIGN_IN -> {
if (resultCode == Activity.RESULT_OK) {
Log.i(TAG, "Signed into drive ok.")
//Create an intent for starting the service
//Add whatever data you need to the intent
val intent = Intent(context, UploadService::class.java)
requireContext().startService(intent)
}
}
}
Then in the UploadService
override fun onHandleIntent(intent: Intent?) {
if (intent == null) {
return
}
val lastSignedInAccount = GoogleSignIn.getLastSignedInAccount(this) ?: throw IllegalStateException("Not logged in")
val driveClient = Drive.getDriveClient(this, lastSignedInAccount)
val driveResourceClient = Drive.getDriveResourceClient(this, lastSignedInAccount)
.... Do what you need to do here
}
Remember to add the service to your AndroidManifest.xml
<service
android:name=".UploadService"
android:enabled="true"
android:exported="false" />
Related
I am using FirebaseUI Auth to authenticate users with gmail. I am signing to with my gmail. In onActivityResult I check result code and it is RESULT_OK. Although when I create IdpResponse from intent, I get null and I can't check whether it's a new user or not.
I have added google-services.json in the application, also added libraries and plugins in gradle.
here is my code :
fun promptUserSignIn() {
val providers = arrayListOf(AuthUI.IdpConfig.GoogleBuilder().build())
startActivityForResult(
AuthUI.getInstance().createSignInIntentBuilder().setAvailableProviders(
providers
).build(), SIGN_IN_REQUEST_CODE
)
}
#Override
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == SIGN_IN_REQUEST_CODE) {
val response = IdpResponse.fromResultIntent(intent)
if (resultCode == Activity.RESULT_OK) {
Log.e(TAG, "response: $response intent: $intent")
}
}
}
I'm trying to accept payment but getting this error in callback of sdk.
Code:
val params = cardInputWidget.paymentMethodCreateParams
if (params != null) {
val confirmParams =
ConfirmPaymentIntentParams.createWithPaymentMethodCreateParams(params, clientSecret)
stripe = Stripe(
applicationContext,
PaymentConfiguration.getInstance(applicationContext).publishableKey)
stripe.confirmPayment(this, confirmParams)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
stripe.onPaymentResult(requestCode, data, object : ApiResultCallback<PaymentIntentResult> {
override fun onSuccess(result: PaymentIntentResult) {
val paymentIntent = result.intent
val status = paymentIntent.status
if (status == StripeIntent.Status.Succeeded) {
val gson = GsonBuilder().setPrettyPrinting().create()
showToast("Payment succeeded " + gson.toJson(paymentIntent))
} else {
showToast("Payment Error: "+paymentIntent.lastPaymentError?.message ?: "")
}
}
override fun onError(e: Exception) {
showToast("Payment failed "+e.message)
}
})
}
onError is getting always called!
This is internal code of sdk:
You are using confirmPayment method instead of confirmSetupIntent method. One is used for confirming payment intents with client secret, and the other one is used for confirming setup intents with client secret. Checkout the stripe documentation for saving and reusing payment methods: https://stripe.com/docs/payments/save-and-reuse
I have a program that allows me to store data(pictures and metadata with the taken picture) during the execution of a picture being taking with the android system camera activity... but I have code in place to make sure that the user enters data into a popup activity before the camera activity is displayed by using the OnActivityResult function(this way the user's photo has information that is stored as metadata in my firebase database). I was wondering If I can set a request code that wouldn't be equal to the REQUESTCODE2 so that under the condition that my back button is pressed(which will still result in the REQUESTCODE2 being returned for the com.example.myapplication.nameofphoto activity, which then will trigger takepic()) I can purposely make sure that the request code is faulty so that takepic() does not trigger and I don't store null data into my database.
for your information: nameofpersonvar , and nameofphotovar are both in a different class and is the information from the popup activity
private const val REQUESTCODE = 2
private const val REQUESTCODE2 = 3
fun take_pic(){
val takephotoIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (takephotoIntent.resolveActivity(this.packageManager) != null) {
startActivityForResult(takephotoIntent, REQUESTCODE)
} else {
Toast.makeText(this, "Unable To access Camera... ", Toast.LENGTH_LONG)
.show()
}
}
photoButton.setOnClickListener {
val action3 = Intent(this , com.example.myapplication.nameofphoto::class.java)
startActivityForResult(action3, REQUESTCODE2 )
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (REQUESTCODE == requestCode && resultCode == Activity.RESULT_OK) {
//Compressing the bitmap(image) into a byte[] to match the input of the .putbytes method
val userimage = data?.extras?.get("data") as Bitmap
val byteoutput = ByteArrayOutputStream()
userimage.compress(Bitmap.CompressFormat.JPEG,100 , byteoutput)
val data = byteoutput.toByteArray()
//ref to the firebase "bucket" database
val storageinfo = FirebaseStorage.getInstance().getReference("/Images" )
//extra data that shows who the images belong to (users)
val metadatastoreage = storageMetadata {
setCustomMetadata("Name of person" , nameofpersonvar)
setCustomMetadata("Name of photo" , nameofphotovar)}
storageinfo.putBytes(data, metadatastoreage)
}else if (requestCode ==REQUESTCODE2) {
take_pic()
}
else {
super.onActivityResult(requestCode, resultCode, data)
}
}
Then why don't you send some result code different from the back press method of the current activity opened and check if the result is successful then take pick otherwise do something.
send this as result code from back press method. RESULT_CANCELED
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (REQUESTCODE == requestCode && resultCode == Activity.RESULT_OK) {
//Compressing the bitmap(image) into a byte[] to match the input of the .putbytes method
val userimage = data?.extras?.get("data") as Bitmap
val byteoutput = ByteArrayOutputStream()
userimage.compress(Bitmap.CompressFormat.JPEG,100 , byteoutput)
val data = byteoutput.toByteArray()
//ref to the firebase "bucket" database
val storageinfo = FirebaseStorage.getInstance().getReference("/Images" )
//extra data that shows who the images belong to (users)
val metadatastoreage = storageMetadata {
setCustomMetadata("Name of person" , nameofpersonvar)
setCustomMetadata("Name of photo" , nameofphotovar)}
storageinfo.putBytes(data, metadatastoreage)
return
}
if (requestCode ==REQUESTCODE2 && resultcode == Activity.RESULT_OK) {
take_pic()
} else {
//back pressed do something.
//finish etc
}
}
Edit: You can override the onBackPressed() in the popup activity and send some data using intent to the parent activity. for ex.
Intent resultIntent = new Intent();
// TODO Add extras or a data URI to this intent as appropriate.
resultIntent.putExtra("user_pic_click", "some data");
setResult(Activity.RESULT_OK, resultIntent);
finish();
I'm Using Firebase prebuild UI in my kotlin application,
it is working great to log in, but I can't logout
I've tried:
logout_button.setOnClickListener {
FirebaseAuth.getInstance().signOut()
LoginManager.getInstance().logOut()
val loginActivity = Intent(this, LoginActivity::class.java)
startActivity(loginActivity)
}
which suppose to logout the user and takes him back to the login screen, in the login screen itself I'm adding this check :
override fun onStart() {
super.onStart()
val user = FirebaseAuth.getInstance().currentUser
if (user != null) {
toast(getString(R.string.logged_in))
val mainActivity = Intent(this, MainActivity::class.java)
startActivity(mainActivity)
} else {
toast(getString(R.string.please_login))
}
}
And here is the activity result for my ActivityLogin:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val response = IdpResponse.fromResultIntent(data)
if (resultCode == Activity.RESULT_OK) {
val user = FirebaseAuth.getInstance().currentUser
if (user != null) {
Toast.makeText(this, getString(R.string.logged_in), Toast.LENGTH_SHORT).show()
val mainActivityIntent = Intent(this, MainActivity::class.java)
startActivity(mainActivityIntent)
}
} else {
// Sign in failed. If response is null the user canceled the
// sign-in flow using the back button. Otherwise check
// response.getError().getErrorCode() and handle the error.
// ...
println("Sign in Failed, Error code: ${response?.error?.errorCode} ")
}
}
}
companion object {
const val RC_SIGN_IN = 1
}
Now after logging out I just get back to the main activity and being logged in again
Note
I'm only using facebook login
private val providers = arrayListOf(
//AuthUI.IdpConfig.EmailBuilder().build(),
//AuthUI.IdpConfig.PhoneBuilder().build(),
//AuthUI.IdpConfig.GoogleBuilder().build(),
AuthUI.IdpConfig.FacebookBuilder().build()
// AuthUI.IdpConfig.TwitterBuilder().build()
)
UPDATE
gettingunresolved reference` error when I try to catch the error :
You can call this as you want to perform action after sign Out.
FirebaseAuth.getInstance().signOut().then(function() {
// Sign-out successful.
val loginActivity = Intent(this, LoginActivity::class.java)
startActivity(loginActivity)
}).catch(function(error) {
// An error happened.
});
I am trying to implement the Firebase AuthUI for a dummy app following the course by google itself on udacity. I am not getting the same output as in the course itself and idk what to do exactly or what is going wrong. Below is the code i have written to start up the AuthUI:
private fun launchSignInFlow() {
val providers =
arrayListOf(
AuthUI.IdpConfig.EmailBuilder().build(),
AuthUI.IdpConfig.GoogleBuilder().build()
)
startActivityForResult(
AuthUI.getInstance().createSignInIntentBuilder().setAvailableProviders(
providers
).build(), SIGN_IN_RESULT_CODE
)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == SIGN_IN_RESULT_CODE) {
val response = IdpResponse.fromResultIntent(data)
if (resultCode == Activity.RESULT_OK) {
Log.i(
TAG,
"Successfully signed in user " +
"${FirebaseAuth.getInstance().currentUser?.displayName}!"
)
} else {
Log.i(TAG, "Sign in unsuccessful ${response?.error?.errorCode}")
}
}
}
this is the output screen/ui that i get from this code
And this is what the output should be like according to the course i am following
What's worse is that even when i try to enter an email to the output i get, the screen gets stuck and does nothing at all. This is the link for the video of google for this specific task
https://youtu.be/JKZpZvbm3Bk