Understanding authentication flow in OneDrive with Android and Rest API - android

I tried implementing a signIn method from the OneDrive API, but I am not sure I correctly understood the workflow.
Basically, on first launch of the app, I want to have both the login window and the "authorise the app to..." window". But then, when the user launches the app again, I would like to be directly connected to the app, without any window.
Instead, with the following code, I keep having the second window (where the user decides to accept the app)
#Override
public void signIn() {
//personal code
linkingStarted = true;
signInStatus = SignInStatus.SIGNING_IN;
activity.setUpWait(R.layout.popup_waitgif_white);
//end of personal code
mAuthClient = AuthClientFactory.getAuthClient(activity.getApplication());
if (mAuthClient.getSession().isExpired() && Util.isConnectedToInternet(activity)) {
activity.alertOnUIThread("Login again");
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
mAuthClient.login(activity, SCOPES, mAuthListener);
}
});
} else if (!Util.isConnectedToInternet(activity)) {
activity.alertOnUIThread(activity.getString(R.string.alert_verifyconnection));
} else {
activity.alertOnUIThread("Resigned In OneDrive");
signInStatus = SignInStatus.SIGNED_IN;
mAuthClient.initialize(SCOPES, new AuthListener() {
#Override
public void onAuthComplete(final AuthStatus status, final AuthSession session, final Object userState) {
if (status == AuthStatus.CONNECTED) {
authToken = session.getAccessToken();
oneDriveService = getOneDriveService();
signInStatus = SignInStatus.SIGNED_IN;
} else {
authenticationFailure();
Log.v(TAG, "Problem connecting");
}
}
#Override
public void onAuthError(final AuthException exception, final Object userState) {
//mAuthClient.login(activity, SCOPES, mAuthListener);
}
}, null, authToken);
}
}
and the AuthClientFactory is just this:
public class AuthClientFactory {
private static AuthClient authClient;
private static final String CLIENT_ID = "00000000XXXXX";
public static AuthClient getAuthClient(Context context) {
if (authClient == null)
authClient = new AuthClient(context, OneDriveOAuthConfig.getInstance(), CLIENT_ID);
return authClient;
}
}

You would have an easier time with the OneDrive SDK for Android, as authentication is a much simpler process.
final MSAAuthenticator msaAuthenticator = new MSAAuthenticator() {
#Override
public String getClientId() {
return "<msa-client-id>";
}
#Override
public String[] getScopes() {
return new String[] { "onedrive.appfolder", "wl.offline_access"};
}
}
final IClientConfig oneDriveConfig = new DefaultClientConfig.createWithAuthenticator(msaAuthenticator);
final IOneDriveClient oneDriveClient = new OneDriveClient
.Builder()
.fromConfig(oneDriveConfig)
.loginAndBuildClient(getActivity());
That will take care of the user authentication flow and then give you a service object that makes interacting with OneDrive straight-forward. See the full example application.

Related

Android ReCaptcha: Checkboxes are not shown

I use Android SafetyNet ReCaptcha to show the Google captcha in my Android app. The problem is that when I test it, the checkboxes are never shown. Instead, the captcha is well shown, and its progress bar is animated a little, and then it finishes without any error, confirming I'm a human. This behavior is normal and there isn't any bug.
But. I would want to force the captcha, which seems to work well as I've described above, to show the checkboxes. By "checkboxes", I mean e.g. "checkboxes showing pedestrian crossings that the human user must claim to recognize by checking". The official documentation doesn't explain how to do it: https://developer.android.com/training/safetynet/recaptcha#send-request
Resources (documentation and StackOverflow)
Documentation : 1 link but unrelevant
I've followed this documentation: https://developer.android.com/training/safetynet/recaptcha#send-request . However, it doesn't give any information about how to solve my problem.
StackOverflow : 1 question but unrelevant
I haven't found any relevant question. I've not found, in fact, any question on how to implement ReCaptcha for Android, except a very short one (which doesn't provide any useful data to solve my problem).
My implementation
I'm going to show you how I've implemented their API ReCaptcha for Android (SafetyNet ReCaptcha) to help you to help me.
The process
My app's users can sign-up, sign-in, sign-out.
When a user starts my app, a splash screen appears. If the user isn't connected, he is invited to touch a button.
2.1. If he touches the button, the ReCaptcha is started.
2.1.1. If the ReCaptcha is successfully completed, then the user can sign-up and sign-in with his Google account (I use Google Firebase Auth and even AuthUI).
2.1.2. Otherwise, nothing occurs : he'll have to re-try to complete ReCaptcha.
Sources
SplashScreen.java (an AppCompatActivity class): The "onClick" event handler listening to the "touch" event on the button
In résumé: I attach the listener to the button. If the latter is clicked, thus, I call verifyWithRecaptcha in a (synchrone! and it's voluntary) Executor. Then I call the Google's servers to be sure the captcha has been completed by a humain being, not by a bot, thanks to my class NetworkUseRecaptcha which provides the result of the Google's servers.
final Context that = this;
button_splash_screen_recaptcha.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Executor executor = new Executor() {
#Override
public void execute(#NonNull Runnable command) {
command.run();
}
};
executor.execute(new Runnable() {
#Override
public void run() {
SafetyNet.getClient(that).verifyWithRecaptcha("PUBLIC KEY")
.addOnSuccessListener(executor,
new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() {
#Override
public void onSuccess(final SafetyNetApi.RecaptchaTokenResponse response) {
String userResponseToken = response.getTokenResult();
if (!userResponseToken.isEmpty()) {
String[] parameters = new String[2];
parameters[0] = "SECRET KEY";
parameters[1] = userResponseToken;
new NetworkUseRecaptcha(new RecaptchaPostExecuteCallback() {
#Override
public void onTaskCompleted(String result, boolean background_error) {
if(background_error) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(that,"Error N°2: Unable to check the captcha.", Toast.LENGTH_SHORT).show();
}
});
return;
}
try {
final JSONObject json_response = new JSONObject(result);
if(!json_response.isNull("success") && json_response.getBoolean("success")) {
final List<AuthUI.IdpConfig> providers = ImmutableList.of(
new AuthUI.IdpConfig.GoogleBuilder().build()
);
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setAlwaysShowSignInMethodScreen(true)
.setLogo(R.drawable.yellow_logo)
.setTheme(R.style.LoginTheme)
.build(),
REQUEST_CODE_SIGN_IN
);
} else {
Toast.makeText(that,"Error N°4: Unable to check the captcha.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(that,"Error N°3: Unable to check the captcha.", Toast.LENGTH_SHORT).show();
}
});
}
}
}).execute(parameters);
}
}
})
.addOnFailureListener(executor, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
System.err.println(e);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(that,"Error N°1: Unable to check the captcha.", Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
}
});
NetworkUseRecaptcha.java: My class that allows me to contact the Google's servers to verify the captcha
class NetworkUseRecaptcha extends AsyncTask<String, Void, String> {
private final RecaptchaPostExecuteCallback post_execute_callback;
private boolean background_error;
NetworkUseRecaptcha(RecaptchaPostExecuteCallback post_execute_callback) {
this.post_execute_callback = post_execute_callback;
background_error = false;
}
#Override
protected String doInBackground(String[] parameters) {
StringBuilder string_builder = new StringBuilder();
try {
URL url = new URL("https://www.google.com/recaptcha/api/siteverify");
HttpsURLConnection https_url_connection = (HttpsURLConnection) url.openConnection();
https_url_connection.setRequestMethod("POST");
https_url_connection.setDoOutput(false);
https_url_connection.setUseCaches(false);
OutputStream os = https_url_connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
writer.write("secret=" + parameters[0] + "&response=" + parameters[1]);
writer.flush();
writer.close();
os.close();
InputStream input_stream = https_url_connection.getInputStream();
BufferedReader buffered_reader = new BufferedReader(new InputStreamReader(input_stream));
String line;
while((line = buffered_reader.readLine()) != null) {
string_builder.append(line);
}
buffered_reader.close();
} catch (Exception e) {
background_error = true;
}
return string_builder.toString();
}
#Override
protected void onPostExecute(String result) {
post_execute_callback.onTaskCompleted(result, background_error);
}
}
https://developers.google.com/android/reference/com/google/android/gms/safetynet/SafetyNetClient#verifyWithRecaptcha(java.lang.String): "If reCAPTCHA is confident that this is a real user on a real device it will return a token with no challenge. Otherwise it will provide a visual/audio challenge to attest the humanness of the user before returning a token."
So my wish is impossible to concretize...

Null pointer exception in creating a dialog in quickblox [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I having some issue in creating a dialog of type group in quickblox chat service on android. I am able to get all the user from the server side of quickblox, able to build dialog and adding those users i got in it but when it comes to call groupChatManager.createDialog(dialog, new QBEntityCallbackImpl(). I am getting a null pointer exception on that. I found later that i have to initialise chatService in class that extends application i did that but still same error. here is my code
enter code here
My applicationSingeltonClass
public class ApplicationSingleton extends Application
{
private QBUser currentUser;
//quickBlox
private static final String APP_ID = "key";
private static final String AUTH_KEY = "authkey";
private static final String AUTH_SECRET = "authsec";
private static ApplicationSingleton instance;
private Map<Integer, QBUser> dialogsUsers = new HashMap<Integer, QBUser>();
private QBRoomChat currentRoom;
#Override
public void onCreate()
{
super.onCreate();
initApplication();
initImageLoader(getApplicationContext());
}
public static ApplicationSingleton getInstance()
{
return instance;
}
private void initImageLoader(Context context)
{
// This configuration tuning is custom. You can tune every option, you may tune some of them,
// or you can create default configuration by
// ImageLoaderConfiguration.createDefault(this);
// method.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.enableLogging() // Not necessary in common
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}
public QBUser getCurrentUser()
{
return currentUser;
}
public void setCurrentUser(QBUser currentUser)
{
this.currentUser = currentUser;
}
public Map<Integer, QBUser> getDialogsUsers()
{
return dialogsUsers;
}
public void setDialogsUsers(List<QBUser> setUsers)
{
dialogsUsers.clear();
for (QBUser user : setUsers)
{
dialogsUsers.put(user.getId(), user);
}
}
public void addDialogsUsers(List<QBUser> newUsers)
{
for (QBUser user : newUsers)
{
dialogsUsers.put(user.getId(), user);
}
}
public Integer getOpponentIDForPrivateDialog(QBDialog dialog)
{
Integer opponentID = -1;
for(Integer userID : dialog.getOccupants())
{
if(userID != getCurrentUser().getId())
{
opponentID = userID;
break;
}
}
return opponentID;
}
private void initApplication()
{
instance = this;
QBChatService.setDebugEnabled(true);
QBSettings.getInstance().fastConfigInit(APP_ID, AUTH_KEY,AUTH_SECRET);
}
}
here is my other class were i create a dialog
enter code here
protected void onPostExecute(final Boolean success)
{
if(status.equals("accepted"))
{
pagedRequestBuilder.setPage(1);
pagedRequestBuilder.setPerPage(10);
final ArrayList<String> usersLogins = new ArrayList<String>();
usersLogins.add(userID);
usersLogins.add(herocivID);
final ArrayList<Integer> occupantIdsList = new ArrayList<Integer>();
occupantIdsList.add(civID);
occupantIdsList.add(heroCivID);
QBUsers.getUsersByFacebookId(usersLogins, pagedRequestBuilder, new QBEntityCallbackImpl<ArrayList<QBUser>>() {
#Override
public void onSuccess(ArrayList<QBUser> users, Bundle params)
{
if (!QBChatService.isInitialized())
{
QBChatService.init(getApplicationContext());
chatService = QBChatService.getInstance();
chatService.addConnectionListener(chatConnectionListener);
}
QBDialog dialog = new QBDialog();
dialog.setName("chat with mostafa wo may");
dialog.setType(QBDialogType.GROUP);
dialog.setOccupantsIds(occupantIdsList);
QBGroupChatManager groupChatManager = chatService.getInstance().getGroupChatManager();
groupChatManager.createDialog(dialog, new QBEntityCallbackImpl<QBDialog>()
{
#Override
public void onSuccess(QBDialog dialog, Bundle args)
{
Log.i("", "dialog: " + dialog);
}
#Override
public void onError(List<String> errors) {
Toast.makeText(getBaseContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onError(List<String> errors)
{
Toast.makeText(getBaseContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
Toast.makeText(getBaseContext(), "you accepted the request", Toast.LENGTH_SHORT).show();
}
else if(status.equals("rejected"))
{
Toast.makeText(getBaseContext(), "you rejected the request", Toast.LENGTH_SHORT).show();
}
}
i need to know were exactly i have to configure the chat service to prevent the null pointer while creating a dialog.
Any help would be appreciated thank you.
You're right,
chatService.getInstance().getGroupChatManager();
is null if you're not logged in ti Chat
so you have to login to chat first and then call this method
I managed to solve this issue.
First you need to check roomChatManager if its equal to null you have to ask the user to login in.
Second in the login wether your using social provider or by mail you have to login to chatService ( ApplicationSingleton.getInstance().chatService.login(userResult);)
ApplicationSingleton is a java class were it extends Application in it you initialise the ChatService.
Thats it now you can create your dialog successfully.

Android Facebook SDK - username is getting null

I am using simple facebbok to integrate facebook to my application.i need to send the facebook username to server.but i got the username as null from profile listner.
here is my code
public void loginToFacebook(View v){
mSimpleFacebook.login(this);
}
OnLoginListener listner = new OnLoginListener() {
#Override
public void onLogin() {
mSimpleFacebook.getProfile(onProfileListener);
}
};
OnProfileListener onProfileListener = new OnProfileListener() {
#Override
public void onComplete(Profile profile) {
System.out.println(profile.getUsername());//getting null here
}
};
I have also tried with the code,
OnLoginListener listner = new OnLoginListener() {
#Override
public void onLogin() {
Profile.Properties properties = new Profile.Properties.Builder()
.add(Properties.USER_NAME)
.add(Properties.ID)
.build();
mSimpleFacebook.getProfile(properties, onProfileListener);
}
};
But the listner is not getting fired in this case.
This is the permission i have given in the Application class
private void configureFacebook() {
Permission[] permissions = new Permission[] {
Permission.USER_ABOUT_ME,
Permission.PUBLIC_PROFILE,
Permission.READ_STREAM,
Permission.EMAIL,
Permission.PUBLISH_ACTION
};
SimpleFacebookConfiguration configuration = new SimpleFacebookConfiguration.Builder()
.setAppId(Constants.FB_APPID)
.setNamespace("namespace")
.setPermissions(permissions)
.build();
SimpleFacebook.setConfiguration(configuration);
}
You can't get username in API v2.0

Facebook Login doesn't work when I use Samsung Android 4.2

When I use HTC Android, it do very well. However, when I use API of Facebook to login using Samsung Android 4.2, I show an Toast message like "login fail please contact the marker of this app and ask them to issue 1732910 to facebook"
Please help me to fix it!
public class FacebookLogin {
/* variable Facebook */
private static final String FACEBOOK_APPID = "578073962236765";
private FacebookConnector facebookConnector;
private final Handler mFacebookHandler = new Handler();
ActivityBase activity;
Request.GraphUserCallback userCallback;
LoginService.OnSwimLogedInEvents swimLoginCallBack;
LoginService loginService;
Dialog changeDialog;
LoadingDialog loadingDialog;
public FacebookLogin(ActivityBase activity, Request.GraphUserCallback userCallback, LoginService.OnSwimLogedInEvents swimLoginCallBack) {
this.activity = activity;
this.loadingDialog = new LoadingDialog();
this.userCallback = userCallback;
this.swimLoginCallBack = swimLoginCallBack;
this.loginService = new LoginService(activity);
this.facebookConnector = new FacebookConnector(FACEBOOK_APPID,
activity, activity, new String[]{
"publish_stream", "email", "user_birthday", "read_stream", "offline_access"});
}
public void login() {
Session.initializeStaticContext(activity);
if (facebookConnector.getFacebook().isSessionValid()) {
facebookConnector.getFacebook().getSession()
.closeAndClearTokenInformation();
}
AuthListener listener = new AuthListener() {
#Override
public void onAuthSucceed() {
doLogin();
}
#Override
public void onAuthFail(String error) {
//(new MessageAlert()).showDialog("Facebook authetication fail\r\nError:" + error, activity);
}
};
SessionEvents.addAuthListener(listener);
facebookConnector.login();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
facebookConnector.getFacebook().authorizeCallback(requestCode, resultCode, data);
}
private void doLogin() {
AsyncTaskBase<Void, Void, Void> t = new AsyncTaskBase<Void, Void, Void>(
activity) {
#Override
protected Void doInBackground(Void... params) {
mFacebookHandler.post(facebookUserInfoRunner);
return super.doInBackground(params);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
};
t.execute();
}
final Runnable facebookUserInfoRunner = new Runnable() {
#Override
public void run() {
loadingDialog.showDialogLoading(activity);
Request.executeMeRequestAsync(facebookConnector.getFacebook()
.getSession(), new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
SwimAccount currentAccount = ((SwimApp) activity.getApplication()).getCurrentAccount();
currentAccount.setAvatarUrl("https://graph.facebook.com/" + user.getId() + "/picture");
currentAccount.setIsLogin(true);
currentAccount.setFirstName(user.getFirstName());
currentAccount.setLastName(user.getLastName());
currentAccount.setStringId(user.getId());
currentAccount.setAccountType("facebook");
currentAccount.setEmail((String) response.getGraphObject().getProperty("email"));
currentAccount.setBirthdate(user.getBirthday());
currentAccount.setGender((String) response.getGraphObject().getProperty("gender"));
if (userCallback != null) {
userCallback.onCompleted(user, response);
}
loginService.login(currentAccount.getEmail(), "", currentAccount.getAccountType(), currentAccount.getStringId(), swimLoginCallBack);
//changeDialog.dismiss();
}
});
}
};
}
Found a solution to my problem. Try deleting the android:noHistory="true" from the Facebook login activity in your manifest. This messes with the authentication flow of the Session.
It looks like people on XDA have had this same problem.
They are claiming that you can try either of these:
(1) "Don't keep activities" option on Settings > Developer Options. If it's ON, then when an app calls some popup, system closes app, so then system restarts it ... and there got your loop.
(2) If you uninstall the Facebook App, you can then login through your app, and then re-install the Facebook app.
Not sure how "official" these answers are, but thought it might be worth a shot to you.
Sources:
http://forum.xda-developers.com/showthread.php?p=43200939 and http://forum.xda-developers.com/showthread.php?t=2186035

Handling a facebook-object through multiple activities

Currently I'm writing an adapter class to provide a convenient way for communication with the facebook API.
The way I thought about using it is to run the authentication when the app is starting up, downloading user's private picture, and later in the app publishing updates on users facebook wall using an AsyncFacebookRunner.
However flipping through the documentation it seems for every authorize() implementation the first parameter have to be an activity.
void authorize(Activity activity, final DialogListener listener):
And here I begin to wonder.
Thinking about activities and life cycles what will happen when the activity I threw in will be destroyed? Wouldn't the reference for this object Facebook.mAuthActivity become invalid as well.
I see the logout() method "only" asks for a context.
String logout(Context context) throws ...:
context - The Android context in which the logout should be called: it should be the same context in which the login occurred in order to clear any stored cookies
From what I see I can not guarantee the "login-activity" will still be present as app's uptime increases - actually the opposite is more likely.
Are there any special situations I should consider to prevent the app form total crashing in a later state?
You can try use my FBHelper class.
public class FBHelper {
private SharedPreferences mPrefs;
private Context context;
private final String ACCES_TOKEN = "access_token";
private final String ACCES_EXPIRES = "access_expires";
private Facebook facebook;
private FBHelperCallbacks callback;
public FBHelper(Context context, Facebook facebook)
{
this.context = context;
this.facebook = facebook;
}
public void setSignInFinishListener(FBHelperCallbacks callback)
{
this.callback = callback;
}
public void FacebookSingleSignIn() {
mPrefs = ((Activity)context).getPreferences(Context.MODE_PRIVATE);
String access_token = mPrefs.getString(ACCES_TOKEN, null);
long expires = mPrefs.getLong(ACCES_EXPIRES, 0);
if(access_token != null) {
facebook.setAccessToken(access_token);
}
if(expires != 0) {
facebook.setAccessExpires(expires);
}
/*
* Only call authorize if the access_token has expired.
*/
if(!facebook.isSessionValid()) {
Log.i("Facebook","Facebook session is not valid based on acces token... authorizing again");
facebook.authorize((Activity)context, new String[] {"user_about_me"},new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
e.printStackTrace();
callback.onError(e.toString());
}
#Override
public void onError(DialogError e) {
Log.i("Facebook","onError inner");
callback.onError(e.toString());
}
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(ACCES_TOKEN, facebook.getAccessToken());
Log.i("Facebook","Saving acces token:"+facebook.getAccessToken());
editor.putLong(ACCES_EXPIRES, facebook.getAccessExpires());
editor.commit();
callback.onSignedInFinished(facebook.getAccessToken());
}
#Override
public void onCancel() {
callback.onError("onCancel");
}
});
}
else
{
Log.i("Facebook","Accces token read form preferencesno no need to authorize");
callback.onSignedInFinished(facebook.getAccessToken());
}
}
public String LogOut()
{
try {
//set ACCES_TOKEN to null
mPrefs = ((Activity)context).getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(ACCES_TOKEN, null);
editor.putLong(ACCES_EXPIRES, 0);
editor.commit();
return facebook.logout(context);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Error";
}
public static abstract class FBHelperCallbacks{
public abstract void onSignedInFinished(String accesToken);
public abstract void onError(String message);
}
}
This is how you use this class.
public class LogInActivity extends Activity {
private static final String TAG = "LogInActivity";
public static final int REQUEST_CODE = 1;
private Context context;
private Facebook facebook;
private FBHelper fbhelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
this.context = this;
Handler pauser = new Handler();
pauser.postDelayed (new Runnable() {
public void run() {
facebook = new Facebook(context.getString(R.string.FACEBOOK_APP_ID));
fbhelper = new FBHelper(context, facebook);
if (aHelper.isLogedIn())
{
//log out
fbhelper.LogOut();
}
else
{
//facebook login
fbhelper.setSignInFinishListener(fbcallback);
fbhelper.FacebookSingleSignIn();
}
}
}, 100);
}
FBHelperCallbacks fbcallback = new FBHelperCallbacks() {
#Override
public void onSignedInFinished(String accesToken) {
Log.d(TAG,"log in finish");
}
#Override
public void onError(String message) {
setResult(RESULT_CANCELED);
finish();
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
aHelper is object that hold some application specific data. Basically you should decide here if you want to log in or log out.
using facebook API for the android is easy and in your case you don't need to save the Facebook instance the only thing you need is to save the authKey of the facebook on the first login then you can use it anywhere.
this means that you can create more than one instance of the facebook object in mutiple activities based on the authKey.
Otherwise you need to put this facebook object in a singleton handler to save it among the application :
class x {
private Facebook obj;
private static x instance;
private x (){
}
public static x getX(){
if(instance == null){
instance = new x();
}
return instance;
}
public void setIt(Facebook obj){
this.obj = obj;
}
public Facebook getIt(){
return obj;
}
}
but this way is not the best way to implement the code you need to create a Facebook instance for each activity using the authKy.

Categories

Resources