使用Active会话可以防止每次在应用程序中登录

时间:2016-05-23 21:00:56

标签: android facebook logout

大家好我实现了请求用户使用他们的Facebook帐户登录的应用程序,但每次退出应用程序并想再次打开应用程序时,它会显示未直接登出的按钮,需要注销并再次登录才能转到下一个活动。你可以建议我修改下面的代码吗?

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;


import kavehkamkar.turnup.Test.R;

import org.json.JSONException;



import com.facebook.Request;
import com.facebook.Request.GraphUserCallback;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.OpenRequest;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity 
{public static ProgressDialog pDialog;
    private UiLifecycleHelper uihelper;  
    LoginButton btn;
    String id,firstname,sex ,birthday;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (isOnline()){    
        uihelper =new UiLifecycleHelper(this,callback);  
         uihelper.onCreate(savedInstanceState);

    btn=(LoginButton)findViewById(R.id.fbbtn);

                 try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.example.testing", 
                    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 (Exception e) 
        {
           e.printStackTrace();
        }
    }
     else{

          AlertDialog.Builder builder = new AlertDialog.Builder(this);

          TextView title =  new TextView(MainActivity.this);
            title.setText("Connection Failed");
            title.setGravity(Gravity.LEFT);
            title.setTextSize(17);
            title.setTypeface(Typeface.DEFAULT_BOLD);

            title.setTextColor(Color.RED);
            builder.setCustomTitle(title);



          builder.setMessage("No Internet connection ! Please check that you have a data connection and then try again.")
                 .setCancelable(false)
                 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int id) {
                          //do things
                         finish();
                         System.exit(0);}
                 });
          AlertDialog alert = builder.create();
          alert.show();
      }


    }


       private boolean isOnline() {
                // TODO Auto-generated method stub
               boolean status=false;
                try{
                    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo netInfo = cm.getNetworkInfo(0);
                    if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
                        status= true;
                    }else {
                        netInfo = cm.getNetworkInfo(1);
                        if(netInfo!=null && netInfo.getState()==NetworkInfo.State.CONNECTED)
                            status= true;
                    }
                }catch(Exception e){
                    e.printStackTrace(); 
                    return false;
                }
                return status;

            }




    void showMsg(String string)
       {
           Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show();
       }

private Session.StatusCallback callback =new Session.StatusCallback() 
         {



            @Override
            public void call(Session session, SessionState state, Exception exception) 
            {

                if (state.isOpened()){
                    Intent in = new Intent("com.example.Test.Profile");
                    Bundle bundle = new Bundle(); 
                    bundle.putString("Fb_id",id);
                      session.getAccessToken()  ;
                    bundle.putString("Fb_name", firstname);
                      session.getAccessToken()  ;
                    bundle.putString("Fb_age", birthday);
                     session.getAccessToken()   ;
                        bundle.putString("Fb_sex", sex);
                    in.putExtras(bundle);
                    startActivity(in);

                      btn.post(new Runnable(){

                            @Override
                            public void run() {
                                btn.setVisibility(View.INVISIBLE);
                                }});

                }
                onSessionStateChange(session,state,exception);
            }
        };

         void onSessionStateChange(final Session session, SessionState state, Exception exception) 
         {

            if (state.isOpened()) 
            {

                Log.i("facebook", "Logged in...");

                Request request=Request.newMeRequest(session, new Request.GraphUserCallback() 
                {   

                    @Override
                    public void onCompleted(GraphUser user, Response response) 
                    {

                        if(user!=null)
                        {

                            Intent in = new Intent("com.example.Test.Profile");
                            Bundle bundle =new Bundle();  
                             bundle.putString("Fb_id", user.getId());
                           if (user.getBirthday() !=null){

                             String agee = "";
                            String[] age= user.getBirthday().split("/");
                             for(int k = 0; k < age.length; k++){
                                 agee=age[2];
                             }
                             int year = Calendar.getInstance().get(Calendar.YEAR);

                             int personage;

                            personage = year -Integer.valueOf( agee);
                             bundle.putString("Fb_age", Integer.toString(personage));
                             birthday=Integer.toString(personage);
                             session.getAccessToken();}

                           bundle.putString("Fb_name", user.getFirstName());
                           if (user.getProperty("gender").toString() !=null){

                              bundle.putString("Fb_sex", user.getProperty("gender").toString());
                              session.getAccessToken();
                              sex=user.getProperty("gender").toString();
                           }
                              in.putExtras(bundle);
                                startActivity(in);
                                 id=user.getId();
                                 session.getAccessToken();
                                 firstname=user.getFirstName();

                        }

                        else
                        {
                            showMsg("its null");
                            showMsg(response.getError().getErrorMessage());
                        }
                    }
                });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,email,birthday,name,first_name,gender");
                request.setParameters(parameters);
                request.executeAsync();

            } 
            else if (state.isClosed()) 
            {
                Log.i("facebook", "Logged out...");
            }
        }    
         public static void logoutFromFB(GraphUserCallback graphUserCallback) {
                Session session = Session.getActiveSession();
                if (session != null) {
                    if (!session.isClosed()) {
                        session.closeAndClearTokenInformation();
                        // clear your preferences if saved
                    }
                } else {
                    session = new Session((Context) graphUserCallback);
                    Session.setActiveSession(session);
                    session.closeAndClearTokenInformation();
                    // clear your preferences if saved
                }}

    @Override
    protected void onResume() {     
        super.onResume();
        if (isOnline()){    uihelper.onResume();    }   

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    uihelper.onSaveInstanceState(outState);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isOnline()){        uihelper.onPause();}
        }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isOnline()){    uihelper.onDestroy();   }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
        super.onActivityResult(requestCode, resultCode, data);
    uihelper.onActivityResult(requestCode, resultCode, data);
    }

    public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
           intent.addCategory(Intent.CATEGORY_HOME);
           intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
           startActivity(intent);
        }

}

2 个答案:

答案 0 :(得分:0)

最新版本sdk 4您可以使用LoginManager.getInstance()。logOut();从facebook登出。在您的任务完成或用户从该屏幕导航的情况下,您可以以编程方式注销。同时初始化你的sdk FacebookSdk.sdkInitialize(getApplicationContext());

如果您使用的是旧版本,则必须使用以下方法清除会话信息

Session session = Session.getActiveSession();
    if (session != null) {

        if (!session.isClosed()) {
            session.closeAndClearTokenInformation();
            //clear your preferences if saved
        }
    } else {

        session = new Session(context);
        Session.setActiveSession(session);

        session.closeAndClearTokenInformation();
            //clear your preferences if saved

    }

答案 1 :(得分:0)

我使用访问令牌解决了这个问题,并将此访问令牌保存在共享首选项中。

package com.example.Test;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Calendar;

import kavehkamkar.turnup.Test.R;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

public class MainActivity extends Activity {

  // Your Facebook APP ID
  private static String APP_ID = "Replace with your App "; // 

  // Instance of Facebook Class
  private Facebook facebook = new Facebook(APP_ID);
  private AsyncFacebookRunner mAsyncRunner;
  String FILENAME = "AndroidSSO_data";
  public static SharedPreferences mPrefs;

  // Buttons
  Button btnFbLogin;


  String access_token;
  long expires;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnFbLogin = (Button) findViewById(R.id.btn_fblogin);


    mAsyncRunner = new AsyncFacebookRunner(facebook);
    mPrefs = getPreferences(MODE_PRIVATE);
    access_token = mPrefs.getString("access_token", null);
     expires = mPrefs.getLong("access_expires", 0);


     if (access_token != null) {
          facebook.authorize(this,
                  new String[] { "email"},
                  new DialogListener() {

                    @Override
                    public void onCancel() {
                      // Function to handle cancel event
                    }

                    @Override
                    public void onComplete(Bundle values) {
                          btnFbLogin.setVisibility(View.INVISIBLE);
                            getProfileInformation();
                          // Making logout Button visible

                          // Making post to wall visible

                    }

                    @Override
                    public void onError(DialogError error) {
                      // Function to handle error

                    }

                    @Override
                    public void onFacebookError(FacebookError fberror) {
                      // Function to handle Facebook errors

                    }

                  });
       }

       if (expires != 0) {
         facebook.setAccessExpires(expires);
       }





    /**
     * Login button Click event
     * */
    btnFbLogin.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        Log.d("Image Button", "button Clicked");
        loginToFacebook();
      }
    });

    /**
     * Getting facebook Profile info
     * */


    /**
     * Posting to Facebook Wall
     * */


    /**
     * Showing Access Tokens
     * */


  }

  /**
   * Function to login into facebook
   * */
  public void loginToFacebook() {

    mPrefs = getPreferences(MODE_PRIVATE);
     access_token = mPrefs.getString("access_token", null);
     expires = mPrefs.getLong("access_expires", 0);

    if (access_token != null) {
      facebook.setAccessToken(access_token);

      btnFbLogin.setVisibility(View.INVISIBLE);

      // Making get profile button visible


      // Making post to wall visible


      // Making show access tokens button visible


      Log.d("FB Sessions", "" + facebook.isSessionValid());
    }

    if (expires != 0) {
      facebook.setAccessExpires(expires);
    }

    if (!facebook.isSessionValid()) {
      facebook.authorize(this,
          new String[] { "email"},
          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();

              // Making Login button invisible
              btnFbLogin.setVisibility(View.INVISIBLE);

              // Making logout Button visible
              getProfileInformation();

              // Making post to wall visible

              // Making show access tokens button 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);
    facebook.authorizeCallback(requestCode, resultCode, data);
  }


  /**
   * Get Profile information by making request to Facebook Graph API
   * */
  @SuppressWarnings("deprecation")
public void getProfileInformation() {
      Bundle params = new Bundle();
      params.putString("fields", "id,email,birthday,name,first_name,gender");

      mAsyncRunner.request("me", params,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);


          final String email = profile.getString("email");

          Intent in = new Intent("com.example.Test.Profile");
          Bundle bundle =new Bundle();  
           bundle.putString("Fb_id", profile.getString("id"));
           if (profile.getString("birthday") !=null){

               String agee = "";
              String[] age= profile.getString("birthday").split("/");
               for(int k = 0; k < age.length; k++){
                 agee=age[2];
               }
               int year = Calendar.getInstance().get(Calendar.YEAR);

               int personage;

              personage = year -Integer.valueOf( agee);
               bundle.putString("Fb_age", Integer.toString(personage));            
           }
           bundle.putString("Fb_name",  profile.getString("name"));

           if (profile.getString("gender").toString() !=null){

               bundle.putString("Fb_sex", profile.getString("gender").toString());
           }


             // Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
                  in.putExtras(bundle);
                  startActivity(in);



        } 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) {
      }
    });


  }

  /**
   * Function to post to facebook wall
   * */
  @SuppressWarnings("deprecation")
public void postToWall() {
    // post on user's wall.
    facebook.dialog(this, "feed", new DialogListener() {

      @Override
      public void onFacebookError(FacebookError e) {
      }

      @Override
      public void onError(DialogError e) {
      }

      @Override
      public void onComplete(Bundle values) {
      }

      @Override
      public void onCancel() {
      }
    });

  }

  /**
   * 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
   * */
  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() {
              // make Login button visible
              btnFbLogin.setVisibility(View.VISIBLE);

              // making all remaining buttons 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) {
      }
    });
  }
  public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
           intent.addCategory(Intent.CATEGORY_HOME);
           intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
           startActivity(intent);
        }
}