how to manage google user(gmail) session using sharedpreferences? - android

I am developing android app. In my app i provided login with google functionality. If i use following code in same activity then it works well for logout from google.-
if (googleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(googleApiClient);
googleApiClient.disconnect();
googleApiClient.connect();
}
Question -
How to manage google user session using SharedPreferences?
or How to initialize googleApiClient object in SessionManager class?
Thanks.

Related

Authentication with Dropbox Api V2 [duplicate]

I've just started out and I'm following this tutorial
https://www.dropbox.com/developers/documentation/java#tutorial
But there's no login. Nothing asks you for a username, password. That means I can't actually get a GUI that every app with "Share to Dropbox" option has.
Am I stuck with one account? Do I have to find a way to get a person's ACCESS_TOKEN or is there a more elegant GUI solution out there(like with Google Drive and their intentsenders)?
To use the Dropbox API v2 in Android, you should use the API v2 Java SDK. There's an example Android app that uses it included with the SDK. You should refer to that as an example of how to implement the app authorization flow, which is accomplished via OAuth 2. That requires the user to authorize your app with Dropbox, by signing in to Dropbox if necessary. After that, your app can store and re-use the resulting access token for that user, as the example does here.
Implementing it that way allows any user to connect their Dropbox account to your app. You can also handle multiple accounts per instance of your app if you want.
Unfortunately, there isn't much out there in terms of documentation for this flow. Here is how I was able to successfully authenticate users. First, you want to launch the authentication flow with Dropbox's auth activity:
import com.dropbox.core.android.Auth
....
Auth.startOAuth2Authentication(context, context.getString(R.string.dbx_api_app_key))
After a user has successfully authenticated, call the following method in the onResume method of the activity you started the Dropbox activity from:
#Override
public void onResume() {
super.onResume();
String token = Auth.getOAuth2Token()
}
The token that you receive here should be used when you create your instance of the DbxClientV2 like so:
DbxRequestConfig requestConfig = DbxRequestConfig.newBuilder(MyUtils.getVersionText(context))
.withHttpRequestor(OkHttp3Requestor(OkHttp3Requestor.defaultOkHttpClient()))
.build()
DbxClientV2 dbxClient = DbxClientV2(requestConfig, accessToken)
You'll also need the following dependencies in your build.gradle file:
implementation 'com.squareup.okhttp:okhttp:2.7.5'
implementation 'com.squareup.okhttp3:okhttp:3.7.0'

Should we create instance of EasyTracker multime times when trying to send logs to Google Analytics dashboard

I am using Google Analytics in android project. For this wherever I'm sending analytics I'm creating object of EasyTracker class.
Suppose user is on First Activity then I'm creating the object of EasyTracker in onCreate so when user navigate to second activity then again I'm creating object of EasyTracker in onCreate of second activity.
Should we create object of EasyTracker once only and use it same in entire application or this does not matter. I guess that by creating two object of EasyTracker Google Analytics is assuming that there are two real time users but exact is only one.
EasyTracker easyTracker = EasyTracker.getInstance(ActivityMain.this);
Thanks in advance.
Look at sample:
#Override
public void onStart() {
super.onStart();
... // The rest of your onStart() code.
EasyTracker.getInstance(this).activityStart(this); // Add this method.
}
#Override
public void onStop() {
super.onStop();
... // The rest of your onStop() code.
EasyTracker.getInstance(this).activityStop(this); // Add this method.
}
https://developers.google.com/analytics/devguides/collection/android/v3/
It seems that EasyTracker is singletone and you should call getInstance every time.
You should consider switching to a newer v4 version of the Google Analytics SDK for Android. v4 of the API support automatic activity reporting - Tracker.enableAutoActivityTracking. Once you enable automatic tracking it does the screen reporting for you. Easy tracker is v2/v3 of the API and doesn't support many new features added to Google Analytics like demographics reporting. Google only maintains the latest version of the SDK so v2/v3 might not work that well on newer versions of Android.

I don't understand how Google Play Games Services work?

I have tried to follow to Google documentation for Google Play Services but that's impossible, because Google documentation is the worst ever.
Anyway, I manged to setup project and add Google Play Services in my app, but I don't know how to keep connected state of player when user changes activity.
I have MainActivity, where extend BaseGameActivity, and then user click on button Play, I open GameActivity, where I play game, and when I finish game I want to submit score to Google Play Services Leaderboard, but I can't because it seems that I am not connected.
I extend MyActivity with BaseGameActivity
public class MainActivity extends BaseGameActivity
Then I on GameActivity extend this:
public GameActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener
And then on onCreate use this:
// Create the Google Api Client with access to Plus and Games
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addOnConnectionFailedListener(this)
.addApi(Plus.API).addScope(Plus.SCOPE_PLUS_LOGIN)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
// add other APIs and scopes here as needed
.build();
And then when I finish game I try to submit score, but it seems that I am not connected.
if(mGoogleApiClient.isConnected()){
Games.Achievements.unlock(mGoogleApiClient,
getString(R.string.app_name));
Games.Leaderboards.submitScore(mGoogleApiClient,
getString(R.string.number_guesses_leaderboard),
clickCounter);
}
According to the docs, you need to call mGoogleApiClient.connect() aswell. They recommend using a button for sign in, but you can also do it at onStart():
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
If all goes well you'll receive the callback onConnected(Bundle connectionHint) which you are already implementing.
Play Game Services are really made with Fragments in mind. It is almost mandatory to use Fragments instead of Activities, and to have a single Activity in your app...

User Sign-out: clearing the default Google account does not cause the account picker to show up in Android app

I followed the below link to implement a "sign out" button in my android app, which uses a Google API client. However, upon connecting the google api again, the user is not presented with an account picker. It looks like the value of her/his original choice is somehow still cached perhaps. I've been trying to figure this out for a few hours.
Any and all ideas very welcome. Thank you.
https://developers.google.com/+/mobile/android/sign-in
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
}
I've had many problems using clearDefaultAccount and trying to reconnect as well. Finally I've decided to separate the account selection process by using the AccountPicker class (which, by the way, doesn't require global permissions in manifest).
So, when the user wants to connect, always show the AccountPicker and then use the selected account to build your GoogleApiClient (see .setAccountName in GoogleApiClient.Builder).
Everything works smoothly now.
This works for me - use revoke to remove all data in the google client:
public void logout()
{
if (mPlusClient.isConnected())
{
Plus.AccountApi.clearDefaultAccount(mPlusClient);
Plus.AccountApi.revokeAccessAndDisconnect(mPlusClient);
}
}
Afterwards, if you try to login again, you'll be presented an account selector again
You are not being presented with an account picker because you didn't call
mGoogleApiClient.connect() after reconnecting.

How to integrate Facebook SDK into Native Android apps

Facebook has a very good documentation of integrating SDKs for Android, iOS & JavaScript etc. But still I have seen some confusions or misunderstandings regarding the exact ways to integrate Facebook SDK.
So I am writing all to the point steps to integrate Facebook SDK in Android Native apps and make use of Graph APIs etc.
In documentation, they have explained it in the way of documentation.
Here I am trying to explain the steps the way we need them while integrating in our app.
I will be giving answers to the most doubts we get, most occurring errors etc.
I hope it will help someone someday.
Facebook provides a wide range of options that can be done by integrating its SDK. But we need to follow some proper steps for the same.
Login
The very first thing we need to do is Login, before our app starts making use of Facebook SDK we need to do authentication. The user must login with his/her account before our app starts getting benefit from
This can be done in two ways,
a) Via Native Android App
If the user is having Facebook app installed in their phones then they will be asked to login via the account they have logged in with in their facebook app.
b) Via Web View
If user is not having facebook app, then facebook login page is opened in a web browser and user can login to their account.
So by any of these two options, once the user logs in then your app gets authenticated to use their account in your app.
How to do this
Once you include Facebook SDK & Library project in your own Android app then you can simply put their built in widget in any of Your xml file and you will see the Login button there. It's code is simple,
<com.facebook.widget.LoginButton
android:id="#+id/authButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
/>
Just include the above mentioned code in your XML file (where ever you want to show Facebook Login button.) It will automatically create the Login button like the following,
Confusions/Doubts/Questions we have in our minds up till this stage
Q. How can I create the button like this in my own app? From where am I going to get logo or what color does it have etc. etc.
Ans. We don't need to create it on our own, we just put that widget in our code and the button is created automatically.
Authorization
Okay, fine we have included the Facebook login button, now user can do login into our app, next what?
Next Facebook provides many kind of options we can do, like Share something on their profile, Post a status or custom story, get user's liked pages, access their messages, posts, feeds, friend list blah blah blah.
But it is not like that user logged in with their account and we can do anything we want in our app with their facebook account.
The next term which comes in to action is Permissions
To perform a specific task we need related permission, if the user will give you permission to do so with their Facebook account, only then our app will be able to do.
For example, to access user's likes we need user_likes permission, to post something on behalf of user on their profile we need publish_actions permission etc. Complete list of permissions can be found here
So after authentication, the next thing is authorization. What our app is authorized to do with user's account.
How to get permissions
As we have already created a Login button for facebook using their button widget, now we can provide the permissions as a list to that button, so it will let the user know about what permissions you want from them when they login with their account.
Clearing the doubt here
YES, the user will be told what permissions your app wants from them while doing login. Simply you can say, the user will be told what your app can do with their facebook account like accessing their friend list, post something on their profile, reading contacts etc. However the user may or may not read it, but the login button let them know about everything.
How to add permissions to Facebook login button
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("user_likes", "user_status", "publish_actions"));
So you can see we are providing a list of permissions we want. However it is even possible to ask for more permissions later on, so it is more advisable to firstly ask for basic permissions and ask for permissions like publish_actions, when user would want it.
Session
Session is a very common term mostly in case of web applications. It serves the similar purpose here. Once the user logs in with their facebook account, a Session is created in your app with the facebook and it remains until the user logs out.
Q. How to show Facebook log out button?
Ans. You will be very happy to hear this, you don't need to do anything to show log out button, once the user logs in, the login button is automatically changed to logout button.
Benefit of Session
Session object has the authentication token that enables us to perform any action with Facebook SDK.
We can get the facebook session object at any time by calling the following method,
Session session = Session.getActiveSession();
UiLifecycleHelper class
Although we have done all the steps, but we need to maintain the session properly then we are going to need this class. We just need to put it in all our activity life cycle methods
so that the facebook session is maintained accordingly.
Define an instance variable in your activity,
private UiLifecycleHelper uiHelper;
Then add the following code,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
Now the facebook session will be maintained automatically without your headache.
Calling the Graph API
I am going to give you a very simple and basic example here, suppose we want to get the list of the pages the user has liked, then we can do it with the following code,
Session session = Session.getActiveSession();
new Request(
session,
"/me/likes",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
//Do what you want to with the response
}
}
).executeAsync();
Q. How it is going to fetch data related to the current user? We have not mentioned any user id any where?
Ans. The answer to this question is that we are using me object here, which will automatically point to the current user who has logged in to using facebook account.

Categories

Resources