I have developed a physics based (Box2d) game for android using Processing and I want to add score sharing option to it so that the user can share his/her best score on their facebook timeline after the game. I have setup Facebook SDK in eclipse. I have searched over internet and found this solution:
public class FacebookConnector {
private static final String APP_ID = "*************";
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
SharedPreferences mPrefs;
public FacebookConnector() {
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
}
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(LocalPakistaniGames.this,
new String[] { "email",
"publish_stream" }, new DialogListener() {
public void onCancel() {
// Function to handle cancel event
}
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
public void onError(DialogError error) {
// Function to handle error
}
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
public void logoutFromFacebook() {
mAsyncRunner.logout(LocalPakistaniGames.this,
new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
// User successfully Logged out
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Name: " + name + "\nEmail: " + email,
Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onIOException1(IOException e, Object state) {
}
public void onFileNotFoundException1(FileNotFoundException e,
Object state) {
}
public void onMalformedURLException1(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
});
}
public void postToWall(int level, int score) {
// post on user's wall.
String msg = "I just made new best score in Level " + level
+ ". My new Best Score is " + score + ". Beat my score!";
final Bundle parameters = new Bundle();
parameters.putString("description", msg);
parameters.putString("picture", "http://i57.tinypic.com/fui2o.png");
parameters.putString("link",
"https://www.facebook.com/LocalPakistaniGamesAndroid");
parameters.putString("name", "Local Pakistani Games");
parameters.putString("caption",
"Share this. Be a part of preserving Pakistani culture.");
LocalPakistaniGames.this.runOnUiThread(new Runnable() {
public void run() {
facebook.dialog(LocalPakistaniGames.this, "feed",
parameters, new DialogListener() {
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
if (values != null) {
Toast.makeText(LocalPakistaniGames.this,
"Shared successfully on your timeline!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
LocalPakistaniGames.this,
"Share cancelled!",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(LocalPakistaniGames.this,
"Facebook Error!",
Toast.LENGTH_SHORT)
.show();
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(LocalPakistaniGames.this,
"Error!", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(LocalPakistaniGames.this,
"Share cancelled!",
Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
Its working fine and giving a pre-filled dialog box where user can either share or close the dialog box. I have checked and It's sharing correctly on Facebook timeline. But the problem is that it is not using Facebook app installed on the device. Its using chrome on my device to login to Facebook.
Is there any way to force it to use Facebook app for android instead of going to chrome (or any other browser)??
There are many issues with your use of the Facebook SDK, but I will jump straight to your problem.
You're using the "feed" dialog to share. This is a web dialog, which is why it's popping up a WebView (not the actual browser app). You also do not pass any session or access tokens to the feed dialog, which is why the user needs to login before they can share.
If you want to share using the Facebook app, I would recommend this doc: https://developers.facebook.com/docs/android/share
If you want to properly use the Facebook SDK (rather than the old deprecated one), please start here: https://developers.facebook.com/docs/android/getting-started/
Here is the solution to your problem. If you want to make automatic publications on facebook wall, you have to use graph api.
Also, the first thing that you have to do is login with facebook and after that, you have to do another request for permissions.
If you are using LoginManager:
LoginManager.getInstance().logInWithPublishPermissions(this, Arrays.asList("publish_actions"));
this line of code gives to your app the permissions to make publications in behalf to the user
Related
Anybody has working sample code for Facebook login in Android using the code snippet mentioned in Facebook developer site ??I couldn't understand it properly.I want to get the name and profile picture of logged in user.I want my app to display the name and profile picture as long as the session is active and need to modify the details if user changed any.
Currently what i do is,saving access token and name in shared preferences on first login and saving the image in sd card and checking access token value during each app launch.If access token value is not null,then i display the name from shared preferences and profile picture from sd card.I know that this is not the right way to do this.Somebody please help me with this.
You can this https://github.com/sromku/android-simple-facebook library it is pretty well defined and can get details of methods by searching simle facebook android on google. Do whatever you want to do with facebook with this library....happy coding
Try this code
public class LoginActivity extends Activity {
private Button butLogin, butMaps, butJackpot, butAdministrator, buttonMenu;
public static String APP_ID = " paste your app_id";
public static Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
public static SharedPreferences mPrefs;
private static final String TAG = "Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginToFacebook();
}
// Method to call the Facebook login
protected void loginToFacebook() {
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
mPrefs = getSharedPreferences("faceBook", MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "email", "public_profile",
"publish_stream" }, Facebook.FORCE_DIALOG_AUTH,
new DialogListener() {
#Override
public void onCancel() {
}
#Override
public void onComplete(Bundle values) {
getProfileInformation();
}
#Override
public void onError(DialogError error) {
}
#Override
public void onFacebookError(FacebookError fberror) {
}
});
} else {
getProfileInformation();
}
}
// FaceBook getting profile information
public void getProfileInformation() {
showLoadingImage();
Helper.setFacebookLogin(getApplicationContext(), true);
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
String json = response;
try {
Log.i("JSOB", json);
JSONObject profile = new JSONObject(json);
try {
Bitmap bmp = null;
URL image_value = new URL("http://graph.facebook.com/"
+ profile.getString("id")
+ "/picture?type=large");
bmp = BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
profile_pic.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
}
String first_name= profile.getString("first_name"));
String last_name=profile.getString("last_name"));
String email=profile.getString("email"));
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
// faceBook login method end
}
In my application i am using Facebook SDK for login in to application. It will work fine without any error in phone but if i am test my in tablet it authorised user and generate the access token also but not fetch the user data. i am follow this link for this code http://sunil-android.blogspot.in/2013/08/facebook-integration-with-android-app.html
i am sharing my imported code part
/**
* Function to login into facebook
* */
#SuppressWarnings("deprecation")
public void loginToFacebook() {
String access_token = obj_pref.get_access_token();
long expires = obj_pref.get_access_expires();
if (access_token != null) {
facebook.setAccessToken(access_token);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "email", "publish_stream",
"user_birthday" }, new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
obj_pref.set_access_token(facebook.getAccessToken());
obj_pref.set_access_expires(facebook.getAccessExpires());
getProfileInformation();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
} else if (facebook.isSessionValid()) {
getProfileInformation();
}
}
/**
* Get Profile information by making request to Facebook Graph API
* */
#SuppressWarnings("deprecation")
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);
obj_pref.set_user_id(profile.getString("email"));
runOnUiThread(new Runnable() {
#Override
public void run() {
new send_fb_data().execute();
// upload user data to my database server
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
can any body help me out for this issue even in tablet it will not give any error ...
im my application,i can login to facebook and get the data,but when i click on logout,and then click on login again,it toast the message already login,but i want after logout,on login it again ask the login id and password,as all login requires.in on destroy i tried to clear the session,but it shows an error null exception in onDestroy. please suggest somthing
MainActivity
public class MainActivity extends Activity {
Facebook fb;
Button login,getData,logout;
ImageView ig;
String app_id;
String access_token;
long expires;
private static AsyncFacebookRunner mAsyncRunner;
private SharedPreferences mPrefs;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
app_id= getString(R.string.app_id);
fb= new Facebook(app_id);
login=(Button) findViewById(R.id.login);
logout=(Button) findViewById(R.id.logout);
getData=(Button) findViewById(R.id.getData);
// ig= (ImageView) findViewById(R.id.profile_pic);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
}
});
getData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProfileInformation();
}
});
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(fb.isSessionValid()){
Session.initializeStaticContext(MainActivity.this.getApplicationContext());
logoutFromFacebook();
}
}
});
mAsyncRunner = new AsyncFacebookRunner(fb);
//updateButtonImage();
try {
PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures)
{
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
Log.e("name not found", e.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
}
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
access_token = mPrefs.getString("access_token", null);
expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
fb.setAccessToken(access_token);
login.setVisibility(View.VISIBLE);
// Making get profile button visible
getData.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + fb.isSessionValid());
}
if (expires != 0) {
fb.setAccessExpires(expires);
Toast.makeText(MainActivity.this, "already login", Toast.LENGTH_LONG).show();}
if (!fb.isSessionValid()) {
fb.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
editor = mPrefs.edit();
editor.putString("access_token",
fb.getAccessToken());
editor.putLong("access_expires",
fb.getAccessExpires());
editor.commit();
// Making Login button invisible
login.setVisibility(View.VISIBLE);
// Making logout Button visible
getData.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
fb.authorizeCallback(requestCode, resultCode, data);
}
#SuppressWarnings("deprecation")
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onIOException(IOException e, Object state) {
}
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
public void onFacebookError(FacebookError e, Object state) {
}
});
}
#Deprecated
public void logoutFromFacebook() {
mAsyncRunner.logout(MainActivity.this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// make Login button visible
login.setVisibility(View.VISIBLE);
// making all remaining buttons invisible
getData.setVisibility(View.INVISIBLE);
}
});
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
#Override protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// if(fb.isSessionValid()){
Session.getActiveSession().closeAndClearTokenInformation();
// }
}
}
It is not guaranteed that onDestroy() method will call always called on activity finish.
So better you put that code of session clear in onPause() method.
UPDATE:
Do One more thing
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("access_token", null);
editor.commit();
SharedPreferences.Editor editor2 = getPreferences(MODE_PRIVATE).edit();
editor2.putLong("access_expires", 0);
editor2.commit();
Add this lines in your facebookLogout() method.
Because In your code I found that you are not checking for the session you checking this two variables to identify whether the user is login or not.
You can't rely to onDestroy to be called just after quiting your activity (finish()). it's usually the case but ondestroy can be called after a considerable delay.
you can call your cleaning code in onPause and you can enhance it like following:
#Override protected void onDestroy() {
super.onDestroy();
Session session = Session.getActiveSession();
if (session != null){
session.closeAndClearTokenInformation();
}
}
it is not known when onDestroy is going to call. it only invoke onStop and then move your activity to back. It is happen because if user again start this application , it will not have to load activity in ram again.because it a costly process to load activity in ram. so dont do any saving of data or any other work in onDestroy.move that work in onPause or in onStop.
read more here
in my application,i can loging through my facebook id.,it i enter another id,it didnot fetch data,as it do for my id.i can't understand what is the problem.when i enter another id,it showing loading,and after that onle blank facebook page is visible.
MainActivity
public class MainActivity extends Activity {
Facebook fb;
Button login,getData,logout;
ImageView ig;
String app_id;
private AsyncFacebookRunner mAsyncRunner;
private SharedPreferences mPrefs;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
app_id= getString(R.string.app_id);
fb= new Facebook(app_id);
login=(Button) findViewById(R.id.login);
logout=(Button) findViewById(R.id.logout);
getData=(Button) findViewById(R.id.getData);
// ig= (ImageView) findViewById(R.id.profile_pic);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
}
});
getData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProfileInformation();
}
});
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(fb.isSessionValid()){
logoutFromFacebook();
}
}
});
mAsyncRunner = new AsyncFacebookRunner(fb);
//updateButtonImage();
try {
PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures)
{
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
Log.e("name not found", e.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
}
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
fb.setAccessToken(access_token);
login.setVisibility(View.VISIBLE);
// Making get profile button visible
getData.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + fb.isSessionValid());
}
if (expires != 0) {
fb.setAccessExpires(expires);
Toast.makeText(getApplication(), "already login", Toast.LENGTH_LONG).show();
//logoutFromFacebook();
}
if (!fb.isSessionValid()) {
fb.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
editor = mPrefs.edit();
editor.putString("access_token",
fb.getAccessToken());
editor.putLong("access_expires",
fb.getAccessExpires());
editor.commit();
// Making Login button invisible
login.setVisibility(View.VISIBLE);
// Making logout Button visible
getData.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
fb.authorizeCallback(requestCode, resultCode, data);
}
#SuppressWarnings("deprecation")
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onIOException(IOException e, Object state) {
}
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
public void onFacebookError(FacebookError e, Object state) {
}
});
}
I had the same problem. I fixed it like this.
Go to Facebook developers page
Apps --> "YourApp" --> Status and Review --> Enable ("Do you want to make this app and all its live features available to the general public?")
Like this
When you create app on Facebook. You might have testing and enabled sandbox mode as shown in image.you need to disable it.
Note: don't look at other settings.it is app for web,similarly you will have sandbox option for mobile app.
Your code is not updated for latest Facebook SDK 3.8, now Facebook provide Default class for Login, Share, Import Photo from Facebook and much more. Please follow this link
https://developers.facebook.com/docs/android/login-with-facebook/
I'm implementing Facebook Login in my android app . The problem is When I run the app , it redirects to the facebook login page on the click of a button in my main activity . When I enter the credentials , a white page is displayed and nothing happens . Also , if I run the app a second time , only the blank page shows up . I tried to toggle on/off the single sign on functionality in the developer settings page of facebook , but it didn't help . Here's my code of the Facebook Login activity .
public class FacebookLogin extends Activity {
// Your Facebook APP ID
private static String APP_ID = "xxxxxxx"; // Replace with your App
// ID
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAsyncRunner = new AsyncFacebookRunner(facebook);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// Start AsyncTASK here
loginToFacebook();
} else {
DialogClass
.createDAlertDialog(
FacebookLogin.this,
"Please Check Internet Connection \n Please Turn on Internet",
true);
}
}
/**
* Function to login into facebook
* */
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
public void onAuthFail(String error) {
Log.e("FB", "AuthFailed: " + error);
Toast.makeText(FacebookLogin.this, "Auth fail",
Toast.LENGTH_LONG).show();
startActivity(new Intent(FacebookLogin.this,
SignIn.class));
}
public void onAuthSucceed() {
Log.e("FB", "AuthSucceed");
Toast.makeText(FacebookLogin.this, "Auth success",
Toast.LENGTH_LONG).show();
startActivity(new Intent(FacebookLogin.this,
Logout.class));
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/**
* Function to show Access Tokens
* */
public void showAccessTokens() {
String access_token = facebook.getAccessToken();
Toast.makeText(getApplicationContext(),
"Access Token: " + access_token, Toast.LENGTH_LONG).show();
}
/**
* Function to Logout user from Facebook
* */
#SuppressWarnings("deprecation")
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
}
I implemented that same for windows phone application. I used to face the same problem. But got it correct.
https://github.com/sravich/MvvmCross-Facebook-Login
You could use this link to check the code and run it in similar fashion for android platform. Logic is the same.