I'm trying to just sign a user to the app to be able to use Google Drive API, but in my activityResults I always get the else statement and that means the user is not authorized or the sign in have failed. Why might this be? I have followed the official docs.
Here is my code:
private static final int REQUEST_CODE_SIGN_IN = 0;
private DriveClient mDriveClient;
private DriveResourceClient mDriveResourceClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signIn();
}
private void initializeDriveClient(GoogleSignInAccount signInAccount) {
mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);
mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);
}
/**
* Starts the sign-in process and initializes the Drive client.
*/
private void signIn() {
Set<Scope> requiredScopes = new HashSet<>(2);
requiredScopes.add(Drive.SCOPE_FILE);
requiredScopes.add(Drive.SCOPE_APPFOLDER);
GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
if (signInAccount != null && signInAccount.getGrantedScopes().containsAll(requiredScopes)) {
initializeDriveClient(signInAccount);
} else {
GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.requestScopes(Drive.SCOPE_APPFOLDER)
.build();
GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
if (resultCode == Activity.RESULT_OK) {
// App is authorized, you can go back to sending the API request
Log.e("SignIn", "App autorizada");
} else {
// User denied access, show him the account chooser again
Log.e("SignIn", "App No Autorizada");
finish();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
Solved my own problem pasting the SHA1 and package name into credentials in my google console, it seemed i was doing something wrong with the credentials.
Code looks fine. Check if you have added google_services.json file in the project. Also check if th SHA1 key is correct.
Related
I want to load a pdf file from external storage (Download/Pdfs/myfile.pdf) using AndroidPdfViewer but it shows blank screen without any error. I tried lots of ways but it's not working.
public class PdfViewActivity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File path = new File(Environment.getExternalStorageDirectory().getPath() + "/Download/Pdfs/myfile.pdf");
PDFView pdfView = findViewById(R.id.pdfView);
pdfView.fromFile(path).load();
I have a pdf file in my "Download/Pdfs/myfile.pdf" and i used the above code to load the file but it's not working.
I have given storage permission manually from settings.
Can anyone please correct me where i am making a mistake.
I have tested your code and it works just fine on Android 10 device. Your are missing something from the below:
1.In Android Manifest File add the READ_EXTERNAL_STORAGE permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
and inside application tag add requestLegacyExternalStorage to true to be able to have access on External Storage on Android 10 device and above.
<application
android:requestLegacyExternalStorage="true"
2.Verify that the pdf exists on the device under "/Download/Pdfs/myfile.pdf" path.
3.Change your activity using the below code by requesting External Storage permission at runtime first in onCreate method:
public class PdfViewActivity2 extends AppCompatActivity {
private static final int READ_STORAGE_PERMISSION_REQUEST_CODE = 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//check if Read External Storage permission was granded
boolean granded = checkPermissionForReadExtertalStorage();
if(!granded){
requestPermissionForReadExtertalStorage();
}
else {
readPdf();
}
}
public boolean checkPermissionForReadExtertalStorage() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int result = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED;
}
return false;
}
public void requestPermissionForReadExtertalStorage() {
try {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_STORAGE_PERMISSION_REQUEST_CODE);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case READ_STORAGE_PERMISSION_REQUEST_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Read Pdf from External Storage
readPdf();
} else {
// permission denied. Disable the functionality that depends on this permission.
}
}
}
}
private void readPdf(){
File path = new File(Environment.getExternalStorageDirectory().getPath() + "/Download/Pdfs/myfile.pdf");
PDFView pdfView = findViewById(R.id.pdfView);
pdfView.fromFile(path).load();
}
}
First, add the library to your build.gradle file
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
To open a PDF file from storage, use this code. There are comments that explain what it does.
public class PdfViewActivity2 extends AppCompatActivity {
// Declare PDFView variable
private PDFView pdfView;
private final int PDF_SELECTION_CODE = 99;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize it
pdfView = findViewById(R.id.pdfView);
// Select PDF from storage
// This code can be used in a button
Toast.makeText(this, "selectPDF", Toast.LENGTH_LONG).show();
Intent browseStorage = new Intent(Intent.ACTION_GET_CONTENT);
browseStorage.setType("application/pdf");
browseStorage.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(browseStorage, "Select PDF"), PDF_SELECTION_CODE);
}
// Get the Uniform Resource Identifier (Uri) of your data, and receive it as a result.
// Then, use URI as the pdf source and pass it as a parameter inside this method fromUri(Uri uri)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PDF_SELECTION_CODE && resultCode == Activity.RESULT_OK && data != null) {
Uri selectedPdfFromStorage = data.getData();
pdfView.fromUri(selectedPdfFromStorage).defaultPage(0).load();
}
}
}
In an Android 10 device your app has no access to external storage.
Unless you add
android:requestLegacyExternalStorage="true"
in application tag of manifest file.
Instead of using fromFile() use fromSource(). i.e. Declare pathe as DocumentSource instead of File.
public class PdfViewActivity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DocumentSource path = new File(Environment.getExternalStorageDirectory().getPath() + "/Download/myfile.pdf");
PDFView pdfView = findViewById(R.id.pdfView);
pdfView.fromSource(path).load();
I need to have my app draw over other apps, and I tried getting SYSTEM_ALERT_WINDOW permission shown below.
public class excessiveusageactivity extends AppCompatActivity {
static final int REQUEST_OVERLAY_PERMISSION = 1; //request code
TextView result;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
result = findViewById(R.id.result);
if (requestCode == REQUEST_OVERLAY_PERMISSION) {
if (Settings.canDrawOverlays(this)) {
Toast permissionok = Toast.makeText(this, "permission granted!", Toast.LENGTH_SHORT);
permissionok.show();
//permission granted do stuff
result.setText("yay");
}else{
Toast permissionnotgrantedtoast = Toast.makeText(this,"permission request failed, try again!", Toast.LENGTH_LONG);
permissionnotgrantedtoast.show();
//permission not granted
result.setText("not granted");
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_excessiveusageactivity);
if(
Settings.canDrawOverlays(this)
) {
// ask for overlay permission
Intent requestoverlaypermissionintent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(requestoverlaypermissionintent, REQUEST_OVERLAY_PERMISSION);
result.setText("here");
}
}
}
I got this code from here by user Jayman Jani.
I wish to make a custom system alert popup when the user uses an app for X minutes/hour consecutively, but I can't seem to find any information on how to set up this popup. I am quite new to all this so it would be great if someone can explain it mostly step-by-step. Thank you!
I have successfully added Google authentication in android app. I am able to login properly without any error. But when i try to logout GoogleApiClient is giving me null so that i am failing to logout successfully. I tried so many answers here but nothing worked for me. Below is the code I entered in my MainActivity.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(ApplicationPreferences.get().isFirstTimeUser()) {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(new Scope(GmailScopes.GMAIL_READONLY))
.requestServerAuthCode(Constants.SERVER_CLIENT_ID, true)
.requestEmail()
.build();
signInButton.setSize(SignInButton.SIZE_STANDARD);
signInButton.setScopes(gso.getScopeArray());
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.sign_in_button:
signIn();
break;
}
}
});
signInButton.setVisibility(View.VISIBLE);
// Build a GoogleApiClient with access to the Google Sign-In API and the
// options specified by gso.
mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
.enableAutoManage(MainActivity.this, MainActivity.this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addConnectionCallbacks(MainActivity.this)
.build();
mGoogleApiClient.connect();
} else {
loadMainActivity();
}
}
}, 2000);
Below is my signOut method as specified by Documentation but i failed to understand their statement You must confirm that GoogleApiClient.onConnected has been called before you call signOut. Need some idea what I am doing wrong here.
if (mGoogleApiClient != null)
{
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
ApplicationPreferences.get().clearAll();
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
}
My OnStart()
#Override
public void onStart() {
super.onStart();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d(TAG, "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else {
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
showProgressDialog();
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(GoogleSignInResult googleSignInResult) {
hideProgressDialog();
handleSignInResult(googleSignInResult);
}
});
}
}
The error, if you say callbacks are not being called, might just be the sign that you may not have connected first. I imagine you have implemented the callbacks and they are not being called?
In any case, to "handle" the error situation, you may want to check if the GoogleApiClient is connected.. like this:
if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
{
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
ApplicationPreferences.get().clearAll();
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
}
else{
Log.w("SomeTag", "It looks like GoogleApiClient is not connected");
}
But I do think you need to check if there are any errors (for instance does onConnectionFailed(ConnectionResult result) get called instead? What error do you see?
Hope this helps.
I have a problem with leadherBoard via Google Games.
I have login into app. login run good.
I have copied some block of code from internet and login run good...
But If I want send score in LatherBoard or work with latherboard.
Games.Leaderboards.submitScore(mGoogleApiClient, getString(LEADERBOARD_ID)), 137);
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mGoogleApiClient,
getString(LEADERBOARD_ID)), REQUEST_LEADERBOARD);
Becoause I testing app I have thise code under Button. But If I press this button Application crashed.
But I don't know why.
I sign in with thise code (code from internet not mine)
#Override
public void onStart() {
super.onStart();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else {
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
// showProgressDialog();
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(GoogleSignInResult googleSignInResult) {
// hideProgressDialog();
handleSignInResult(googleSignInResult);
}
});
}
}
// [START onActivityResult]
#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);
handleSignInResult(result);
}
}
// [END onActivityResult]
// [START handleSignInResult]
private void handleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
mStatusTextView.setText(getString(R.string.signed_in_fmt, acct.getDisplayName()));
updateUI(true);
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
// [END handleSignInResult]
// [START signIn]
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
// [END signIn]
// [START signOut]
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
// [START_EXCLUDE]
updateUI(false);
// [END_EXCLUDE]
}
});
}
// [END signOut]
// [START revokeAccess]
private void revokeAccess() {
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
// [START_EXCLUDE]
updateUI(false);
// [END_EXCLUDE]
}
});
}
// [END revokeAccess]
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
}
private void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
private void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.hide();
}
}
private void updateUI(boolean signedIn) {
if (signedIn) {
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
} else {
mStatusTextView.setText(R.string.signed_out);
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
}
}
public void Login(){
// Views
mStatusTextView = (TextView) findViewById(R.id.status);
// Button listeners
findViewById(R.id.sign_in_button).setOnClickListener(this);
findViewById(R.id.sign_out_button).setOnClickListener(this);
findViewById(R.id.disconnect_button).setOnClickListener(this);
// [START configure_signin]
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
// [END configure_signin]
// [START build_client]
// Build a GoogleApiClient with access to the Google Sign-In API and the
// options specified by gso.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// [END build_client]
// [START customize_button]
// Customize sign-in button. The sign-in button can be displayed in
// multiple sizes and color schemes. It can also be contextually
// rendered based on the requested scopes. For example. a red button may
// be displayed when Google+ scopes are requested, but a white button
// may be displayed when only basic profile is requested. Try adding the
// Scopes.PLUS_LOGIN scope to the GoogleSignInOptions to see the
// difference.
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_STANDARD);
signInButton.setScopes(gso.getScopeArray());
// [END customize_button]
}
I don't know what problem are crashed application because in genymotion i can't use login. and my mobile can't use adb driver. Please Help me.
or give mi advice where I can download runing code with leadherboards I will try understanding and use in my application.
Thanks.
Edit
Log? from firebase
Exception java.lang.IllegalStateException: GoogleApiClient is not configured to use the Games Api. Pass Games.API into GoogleApiClient.Builder#addApi() to use this feature.
com.google.android.gms.common.internal.zzaa.zza ()
com.google.android.gms.games.Games.zzc ()
com.google.android.gms.games.Games.zzb ()
com.google.android.gms.games.internal.api.LeaderboardsImpl.submitScore ()
com.google.android.gms.games.internal.api.LeaderboardsImpl.submitScore ()
sk.atest.paradox02.animacia.Index.onClick (Index.java:963)
android.view.View.performClick (View.java:5207)
android.view.View$PerformClick.run (View.java:21177)
android.os.Handler.handleCallback (Handler.java:739)
android.os.Handler.dispatchMessage (Handler.java:95)
android.os.Looper.loop (Looper.java:148)
android.app.ActivityThread.main (ActivityThread.java:5438)
This code is working well when I uninstalled the Facebook App but didn't work with Facebook App installed. I'm using Facebook SDK 4.0.
This is my code
package com.example.nhp04.gqfood;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class Login extends AppCompatActivity implements Animation.AnimationListener {
private String info = "";
private LoginButton loginButton;
private CallbackManager callbackManager;
private AccessTokenTracker tracker;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_login);
loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
info = ("User ID: " +
loginResult.getAccessToken().getUserId() + "\n" + "Auth Token: " + loginResult.getAccessToken().getToken());
}
#Override
public void onCancel() {
info = ("Login attempt canceled.");
}
#Override
public void onError(FacebookException e) {
info = ("Login attempt failed.");
}
});
System.out.println(info);
tracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
}
};
tracker.startTracking();
}
}
this function for checking login
public boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}
this on Resume and on Stop methods
#Override
protected void onResume() {
super.onResume();
if (isLoggedIn()){
Intent home = new Intent(this, home.class);
startActivity(home);
}
}
#Override
protected void onStop() {
super.onStop();
tracker.stopTracking();
finish();
}
And this is my onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Intent home = new Intent(this, home.class);
startActivity(home);
} else {
Toast.makeText(getApplicationContext(), "Unable to login please check your internet connection",Toast.LENGTH_LONG).show();
}
}
where is your onActivityResult() code. In onActivityResult() you need to use callbackmanager. User below code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
above will work both in fragment/activity. Make sure you have
1. facebook app installed on your testing device
2. In facebook developer account check whether you have mentioned
- correct package name : refer your android project manifestfile.xml
- check that have you mentioned correct launcher class
- Check that you have given correct debug/release hash key
3. Cross check your facebook application id and that mentioned in your manifestfile.xml facebook meta data are same
In your code
change below
create you callbackmanager after setContentView(...);
change it to below
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
Remember if this is with you facebook issue then your problem lies within this dont waste time in searching other thing. Also put log in failure method in callback of facebook sdk.
Post comment if you still have problem
you can remove your app in your facebook app. like you can open facebook app in go
setting>>account setting>>app>>youer App >> remove . after remove youer app it uninstall your app .and reinstall it and check login with facebook is working or not.
Please change your facebook sdk version, after you clean and rebuild your application it will work
if you're getting an error message that looks like this:
Error
Invalid key hash. The key hash "...5GAvm/gHi..." does not match any
stored key hashes. Configure your app key hashes at
https://developers.facebook.com/apps/...55.../
then copy the hash key provided in the error message and replace the old one with it and try again with the Facebook app installed on your device