通过Facebook登录我的应用程序

时间:2015-09-28 11:23:54

标签: android facebook-login

我已经制作了facebook的登录示例应用程序,但无法使用facebook登录我自己的应用程序。我无法对其进行任何操作

 public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
       TextView textView = (TextView) view.findViewById(R.id.textView);
        LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);

        loginButton.setReadPermissions("user_friends");
        loginButton.setFragment(this);
        loginButton.registerCallback(callbackManager, callback);




    }

2 个答案:

答案 0 :(得分:0)

在onCreateViiew中使用此代码

LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    Log.d("Success", "Login");

            //code for success

                }

                @Override
                public void onCancel() {

                }

                @Override
                public void onError(FacebookException exception) {
                    // toast
                }
            });

并添加onClick FB登录按钮的代码

LoginManager.getInstance().logInWithReadPermissions(this,
            Arrays.asList("email", "user_likes"));

并在onActivityResult

中提及此行
callbackManager.onActivityResult(requestCode, responseCode, intent);

答案 1 :(得分:0)

尝试以下示例,

在您的项目中添加FacebookSdk并遵循代码。

Main.java

public class LoginWithFacebook extends Activity {

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

    // Instance of Facebook Class
    private Facebook facebook;
    @SuppressWarnings({ "unused", "deprecation" })
    private AsyncFacebookRunner mAsyncRunner;
    String FILENAME = "AndroidSSO_data";
    private SharedPreferences mPrefs;
    LoginButton btnLogin;
    private UiLifecycleHelper uiHelper;
    AQuery aQuery;
    Button login;

    String url,id,name,first_name,middle_name,last_name,location,gender,mobile_number,birthday;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_with_facebook);

        login=(Button)findViewById(R.id.button1);
        btnLogin=(LoginButton)findViewById(R.id.authButton);
        login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                btnLogin.performClick();
            }
        });
        aQuery= new AQuery(getApplicationContext());
        uiHelper = new UiLifecycleHelper(this, callback);
        uiHelper.onCreate(savedInstanceState);
    }


    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state,
                Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };


    // When session is changed, this method is called from callback method
    private void onSessionStateChange(Session session, SessionState state,
            Exception exception) {
        if (state.isOpened()) {
            Log.i("Tag", "Logged in...");
            // make request to the /me API to get Graph user
            Request.newMeRequest(session, new Request.GraphUserCallback() {

                @Override
                public void onCompleted(GraphUser user, Response response) {
                    if (user != null) {
                        Log.v("url aq", "http://graph.facebook.com/"+user.getId()+"/picture?type=large");

                        id=user.getId();
                        name=user.getName();
                        gender=user.getProperty("gender").toString();
                        String userName=user.getProperty("email").toString();
                        url="http://graph.facebook.com/"+user.getId()+"/picture?type=large";

                        callFacebookLogout(getApplicationContext());

                        Intent i=new Intent(LoginWithFacebook.this,GetDetail.class);
                        i.putExtra("id",id);
                        i.putExtra("name", name);
                        i.putExtra("gender", gender);
                        i.putExtra("url", url);
                        i.putExtra("username", userName);
                        startActivity(i);
                        finish();

                    }
                }
            }).executeAsync();
        } else if (state.isClosed()) {
            Log.i("Tag", "Logged out...");
//            otherView.setVisibility(View.GONE);
        }
    }

    public static void callFacebookLogout(Context context) {
        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

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_login_with_facebook, menu);
        return true;
    }

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

        uiHelper.onActivityResult(requestCode, resultCode, data);
        Log.i("Tag", "OnActivityResult...");
    }

    @Override
    public void onResume() {
        super.onResume();
        uiHelper.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
    }

}

GetDetail.java

public class GetDetail extends Activity{

    Button btnBack;
    TextView tvId,tvName,tvGender;
    ImageView ivMypic;
    AQuery aQuery;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.get_detail);

        btnBack=(Button)findViewById(R.id.btnBack);

        tvId=(TextView)findViewById(R.id.tvId);
        tvName=(TextView)findViewById(R.id.tvName);
        tvGender=(TextView)findViewById(R.id.tvGender);

        ivMypic=(ImageView)findViewById(R.id.ivMypic);

        aQuery=new AQuery(GetDetail.this);

        Intent i=getIntent();
        tvId.setText("Id: "+i.getStringExtra("id"));
        tvName.setText("Name: "+i.getStringExtra("name"));
        tvGender.setText("Gender: "+i.getStringExtra("gender")+" UserName = "+i.getStringExtra("username"));
        String imageUrl=i.getStringExtra("url");
        aQuery.id(ivMypic).image(imageUrl,false,true);
        btnBack.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent login= new Intent(GetDetail.this,LoginWithFacebook.class);
                startActivity(login);
                finish();
            }
        });
    }
}

和main.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    <ImageView
        android:id="@+id/ivProfile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/ic_launcher" />

    <LinearLayout
        android:id="@+id/other_views"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical"
        android:padding="5dp" >

        <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:gravity="left"
            android:text="Name"
            android:textSize="30dp" />

        <TextView
            android:id="@+id/gender"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:gravity="left"
            android:text="Gender"
            android:textSize="15dp" />

        <TextView
            android:id="@+id/location"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:gravity="left"
            android:text="Location"
            android:textSize="15dp" />
    </LinearLayout>

        <com.facebook.widget.LoginButton
            android:id="@+id/authButton"
            android:visibility="gone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="30dp"
            />

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Login" />

    </LinearLayout> 

get_detail.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnBack"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back" />

    <ImageView
        android:id="@+id/ivMypic"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_gravity="center_vertical"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/tvId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:gravity="center_vertical"
        android:layout_marginBottom="20dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/tvName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:gravity="center_vertical"
        android:layout_marginBottom="20dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />


    <TextView
        android:id="@+id/tvGender"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:gravity="center_vertical"
        android:layout_marginBottom="20dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

manifest.xml是。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.loginwithfacebook"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />

        <activity
            android:name="com.example.loginwithfacebook.LoginWithFacebook"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.facebook.LoginActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
        <activity android:name=".GetDetail" />

    </application>

</manifest>