I am following this tutorial for integrating Facebook SDK for Android. It works perfectly. My problem is that what if I want to log out of the Facebook (like closing the session). How to do log in and log out on same Button.
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i=new Intent(this,MainActivity.class);
startActivity(i);
}
});
Following is my code:
public class MainActivity extends Activity {
private Button button1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Session.openActiveSession(this, true, new StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
// TODO Auto-generated method stub
Request.executeMeRequestAsync(session,new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// TODO Auto-generated method stub
if(user!=null){
TextView tv1=(TextView)findViewById(R.id.textview1);
tv1.setText("Hello "+user.getName()+ ";");
}
}
});
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}
I want to log in and log out on buttonClick. Can anyone help?
Thanks in advance.
Call this method.you will logout from the session
session.closeAndClearTokenInformation();
Related
I am trying to get the facebook login for authentication in my app it is done but the problem is when i tried to logout inside the logout its not working can anyone help me please. the code is give below
public class Facebooklogin extends Activity implements OnClickListener
{
ImageView ivFacebook,btnLogout;
Facebook fb;
public static final String MyPREFERENCES = "MyPrefs" ;
String APP_ID;
private SharedPreferences sp;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginscreen);
sp=getPreferences(Context.MODE_PRIVATE);
String access_token=sp.getString("access_token", null);
long expires=sp.getLong("access_expires", 0);
if(access_token !=null)
{
fb.setAccessToken(access_token);
}
if(expires !=0)
{
fb.setAccessExpires(expires);
}
APP_ID=getString(R.string.facebook_app_id);
fb=new Facebook(APP_ID);
ivFacebook=(ImageView)findViewById(R.id.ivFacebook);
ivFacebook.setOnClickListener(this);
}
#SuppressWarnings("deprecation")
private void updateButton()
{
// TODO Auto-generated method stub
Intent i = new Intent(Facebooklogin.this,MainAct.class);
startActivity(i);
}
#SuppressWarnings("deprecation")
public void onClick(View v)
{
// TODO Auto-generated method stub
if(fb.session != null && fb.session.isOpened())
{
try {
// fb.logout(getApplicationContext());
updateButton();
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
fb.authorize(Facebooklogin.this, new String[] {"email"},new DialogListener()
{
#Override
public void onFacebookError(FacebookError e)
{
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e)
{
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values)
{
// TODO Auto-generated method stub
Editor editor=sp.edit();
editor.putString("access_token", fb.getAccessToken());
editor.putLong("access_expires", fb.getAccessExpires());
editor.commit();
updateButton();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
}
}
#SuppressWarnings("deprecation")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
fb.authorizeCallback(requestCode, resultCode, data);
}
I do not see any lines for logout here, you can clear the session in order to perform the logout.
if (session != null){
session.closeAndClearTokenInformation();
session = null;
}
Also remove the tokens from the shared preferences and , note that you are using tan older version of facebook api here. Above methods are deprecated now.
I am new to android. I am developing an application which requires facebook login to proceed. So for this I have followed this tutorial - https://developers.facebook.com/docs/android/getting-started
EDIT: Using UILifecycleHelper, same thing happen, once user authenticates the application application is closed.
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Log.w("Vinit", "Session started");
// make request to the /me API
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
TextView t = (TextView) findViewById(R.id.textView1);
t.setText("User: " + user.getFirstName());
}
}
}).executeAsync();
}
}
};
private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
#Override
public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
}
#Override
public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
Log.d("HelloFacebook", "Success!");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
if(new LoginChecker(this).isRegistered()){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}else{
setContentView(R.layout.activity_login);
LoginButton loginButton = (LoginButton) findViewById(R.id.loginButton1);
thisActivity = this;
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
uiHelper = new UiLifecycleHelper(thisActivity, callback);
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.w("Vinit", "On Activity Result function");
uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
}
Use UiLifecycleHelper
https://developers.facebook.com/docs/reference/android/current/class/UiLifecycleHelper
to be sure that your activity/fragment handle processing from facebook component in proper way.
Check Facebook Session object.
Does app call instructions inside session.IsOpened()? Try debug your code to see state of the Facebook Session.
I'm developing android app and i want user to connect Facebook when he open the app for the first time using Facebook SDK.
Then i want to post to the Facebook wall with specific message from my app. I try to use Facebook sdk with my app.I have made integration between mp app and Facebook sdk but i don't know how to do the task that log in to Facebook and post to the wall with the specific message.I search stackoverflow for this task and i found this code but i can't understand it
and it doesn't for me
public class MainActivity extends Activity {
Facebook facebookClient;
SharedPreferences mPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
facebookClient=new Facebook("fb_App_id");
ImageButton facebookButton = (ImageButton) findViewById(R.id.button_FacebookShare);
facebookButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
if (facebookClient.isSessionValid()) {
postToWall();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebookClient.authorizeCallback(requestCode, resultCode, data);
}
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) {
facebookClient.setAccessToken(access_token);
}
if (expires != 0) {
facebookClient.setAccessExpires(expires);
}
if (!facebookClient.isSessionValid()) {
facebookClient.authorize(this, new String[] { "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", facebookClient.getAccessToken());
editor.putLong("access_expires", facebookClient.getAccessExpires());
editor.commit();
postToWall();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
private void postToWall() {
Bundle parameters = new Bundle();
parameters.putString("name", "Battery Monitor");
parameters.putString("link", "https://play.google.com/store/apps/details?id=com.ck.batterymonitor");
parameters.putString("picture", "link to the picture");
parameters.putString("display", "page");
// parameters.putString("app_id", "228476323938322");
facebookClient.dialog(MainActivity.this, "feed", parameters, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
}
}
You should refer to the following question on SO.
Facebook login and post
This code works. It will definitely solve your problem.
Try to use Android Simple Facebook (https://github.com/sromku/android-simple-facebook) - it's a layer to make the usage of Facebook SDK easier. According to the documentation, the login process would be something like this:
Initialize callback listener:
OnLoginListener onLoginListener = new OnLoginListener() {
#Override
public void onLogin() {
// change the state of the button or do whatever you want
Log.i(TAG, "Logged in");
}
#Override
public void onNotAcceptingPermissions(Permission.Type type) {
// user didn't accept READ or WRITE permission
Log.w(TAG, String.format("You didn't accept %s permissions", type.name()));
}
/*
* You can override other methods here:
* onThinking(), onFail(String reason), onException(Throwable throwable)
*/
};
Login:
mSimpleFacebook.login(onLoginListener);
As new to android and with facebook sdk but tried to login by following the link
as they say it will do the login process with facebook but nothing happen and it everytime showing the logged out state.
here is the activity class.
public class MYFaceLoginActivity extends FragmentActivity {
private LoginFragment loginfragment;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
if(savedInstanceState==null)
{
loginfragment=new LoginFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, loginfragment).commit();
}
else
{
loginfragment=(LoginFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//loginfragment.onActivityResult(requestCode, resultCode, data);
}
}
next is the fragment class
public class LoginFragment extends Fragment
{
private View login_view;
private static final String TAG="LoginFragment";
private UiLifecycleHelper uihelper;
private LoginButton authbutton;
private Session.StatusCallback callback=new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
// TODO Auto-generated method stub
onSessionStatechange(session, state, exception);
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
login_view=inflater.inflate(R.layout.login_fragment, container,false);
authbutton=(LoginButton) login_view.findViewById(R.id.authButton);
authbutton.setFragment(this);
authbutton.setReadPermissions(Arrays.asList("user_likes","user_status"));
return login_view;
}
private void onSessionStatechange(Session session,SessionState state,Exception exception)
{
if(state.isOpened()){
Log.i(TAG, "LOGGED IN....");
}
else
{
Log.i(TAG, "LOGGED OUT....");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
uihelper=new UiLifecycleHelper(getActivity(), callback);
uihelper.onCreate(savedInstanceState);
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
Session session=Session.getActiveSession();
if((session!=null)&&(session.isOpened()||session.isClosed()))
{
onSessionStatechange(session, session.getState(), null);
}
uihelper.onResume();
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
uihelper.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
uihelper.onSaveInstanceState(outState);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
uihelper.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
uihelper.onActivityResult(requestCode, resultCode, data);
}
}
can anyone point out what i m doing wrong here.Thanks for any reply and with this facebook login new 3.0 stuck for three day.
Please make changes in MYFaceLoginActivity file
getSupportFragmentManager().beginTransaction().add(
android.R.id.content,loginfragment).commit();
Insted use:
getSupportFragmentManager().beginTransaction().add(R.id.content, loginfragment).commit();
loginfragment=(LoginFragment) getSupportFragmentManager().findFragmentById(R.id.content);
I look all the internet and couldn't find how do I post link with a specific picture on facebook wall using fb sdk\api.
I know that this is part of the code that I need to use:
Facebook facebookClient = new Facebook("fb_App_id");
Bundle parameters = new Bundle();
parameters.putString("message", "Test Photo");
parameters.putString("link", "https://www.google.com");
parameters.putString("picture", "link to some pictrue");
facebookClient.dialog(MainActivity.this, "stream.publish", parameters, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
When I try to use this code I get "Source not found" error.
I think that I'm missing the connect\verification step...
How can I make it work?
Another thing: In case I use FB SDK in my personal app that I share on Google Play and this app is FREE but has Ads on it, Is it legal to use FB SDK in my app?
Finally I found how to do it.
You need to declare this two:
Facebook facebookClient;
SharedPreferences mPrefs;
In the onCreate function I initialize facebookClient with the facebook AppID.
The class that lunches the facebook share must be Activity
There are three functions that I added to the activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebookClient.authorizeCallback(requestCode, resultCode, data);
}
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) {
facebookClient.setAccessToken(access_token);
}
if (expires != 0) {
facebookClient.setAccessExpires(expires);
}
if (!facebookClient.isSessionValid()) {
facebookClient.authorize(this, new String[] { "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", facebookClient.getAccessToken());
editor.putLong("access_expires", facebookClient.getAccessExpires());
editor.commit();
postToWall();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
private void postToWall() {
Bundle parameters = new Bundle();
parameters.putString("name", "Battery Monitor");
parameters.putString("link", "https://play.google.com/store/apps/details?id=com.ck.batterymonitor");
parameters.putString("picture", "link to the picture");
parameters.putString("display", "page");
// parameters.putString("app_id", "228476323938322");
facebookClient.dialog(MainActivity.this, "feed", parameters, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
}
and at last:
ImageButton facebookButton = (ImageButton) findViewById(R.id.button_FacebookShare);
facebookButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
if (facebookClient.isSessionValid()) {
postToWall();
}
}
});
It does an auto login to facebook and then displaies facebook share\post dialog.
The code was taken from this tutorial
I'm guessing that your problem is that you are using the stream.publish path which got deprecated:
Please note: We are in the process of deprecating the REST API, so if
you are building a new application you shouldn't use this function.
Instead use the Graph API and POST a Post object to the feed
connection of the User object
instead do this:
facebookClient.dialog(MainActivity.this, "feed", parameters, new DialogListener() {
...
});