在Android应用程序中将登录与Facebook集成

时间:2015-04-02 06:32:14

标签: android json facebook token

作为初学者,我正在尝试在我的应用程序中实现facebook集成。我让应用程序运行。然而,作为儿子,当我输入我的凭据并且它要求我的许可时,该应用程序崩溃了。我不知道什么是错的。我按照教程here

这是我的主要活动代码:

package com.techfrk.facebooktesting;

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

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import facebook.android.DialogError;
import facebook.android.Facebook;
import facebook.android.Facebook.DialogListener;
import facebook.android.FacebookError;

public class MainActivity extends ActionBarActivity 
{
    private Facebook facebook;
    private static final String APP_ID = "758322840932665";
    private static final String[] PERMISSIONS = new String[] { "publish_stream","read_stream"};
    public static final String TOKEN = "access_token";
    public static final String EXPIRES = "expires_in";
    private static final String KEY = "facebook-credentials";
    Button bb;

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

        bb=(Button)findViewById(R.id.btnLoginNPublish);
        bb.setOnClickListener(new OnClickListener() 
        {

            @Override
            public void onClick(View v) 
            {
                // TODO Auto-generated method stub
                try
                {


                //loginToTwitter();
                 //MyTwitterLogin();
        /////////////// Facebook//////////////
                    facebook = new Facebook(APP_ID);

                    LoginToFacebook();
               //     postToWall("Posting from my Eclipse project!!!");
                  //  fetchFacebookFriends();
                    ///////////////////////
                }
                catch(Exception ex)
                {
                 Log.i("Exception:",ex.getMessage());

                }
            }
        });
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) 
        {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public boolean saveCredentials(Facebook facebook) 
    {
        Editor editor = getApplicationContext().getSharedPreferences(KEY,Context.MODE_PRIVATE).edit();
        editor.putString(TOKEN, facebook.getAccessToken());
        editor.putLong(EXPIRES, facebook.getAccessExpires());
        return editor.commit();
    }

    public boolean restoreCredentials(Facebook facebook) 
    {
        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE);
        facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
        facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
        return facebook.isSessionValid();
    }
    public void LoginToFacebook() 
    {
        facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,new LoginDialogListener());
    }
    public void postToWall(String msg) 
    {
        Log.d("Tests", "Testing graph API wall post");
         try 
         {
                String response = facebook.request("me");
                Bundle parameters = new Bundle();
                parameters.putString("message", msg);
                parameters.putString("description", "test test test");
                response = facebook.request("me/feed", parameters,"POST");
                Log.d("Tests", "got response: " + response);
                if (response == null || response.equals("") || response.equals("false")|| response.contains("error")) 
                {
                   Log.v("Error", response.toString());
                }
         } 
         catch(Exception e) 
         {
             e.printStackTrace();
         }
    }

    public void fetchFacebookFriends()
    {
         try {
                String response = facebook.request("me");

                response = facebook.request("me/friends");

                Log.d("Tests", "got response: " + response);
                if (response == null || response.equals("") || response.equals("false")|| response.contains("error")) 
                {
                   Log.v("Error", response.toString());
                }
                else
                {
                        JSONObject jsonObject = new JSONObject(response);
                        try 
                        {
                            JSONArray array = jsonObject.getJSONArray("data");
                            for (int i = 0; i < array.length(); i++) 
                            {
                                JSONObject object = (JSONObject) array.get(i);
                                Log.d( "id = "+object.get("id"),"Name = "+object.get("name"));
                            }
                        } 
                        catch (JSONException e) 
                        {
                            e.printStackTrace();
                        }
                }
         }
         catch(Exception ex1)
         {

         }
}
    public void fetchMyFacebookStatuses()
    {
         try {
                String response = facebook.request("me");

                response = facebook.request("me/statuses");

                Log.d("Tests", "got response: " + response);
                if (response == null || response.equals("") || response.equals("false")) 
                {
                   Log.v("Error", response.toString());
                }
                else
                {
                        JSONObject jsonObject = new JSONObject(response);
                        try 
                        {
                            JSONArray array = jsonObject.getJSONArray("data");
                            for (int i = 0; i < array.length(); i++) 
                            {
                                JSONObject object = (JSONObject) array.get(i);
                                Log.d( "Message id = "+object.get("id"),"Message = "+object.get("message"));
                            }
                        } 
                        catch (Exception e) 
                        {
                            Log.i("Error in Statuses:",e.getMessage());
                        }
                }
         }
         catch(Exception ex1)
         {
             Log.i("Error in Statuses:",ex1.getMessage());
         }
  }

    class LoginDialogListener implements DialogListener 
    {
        public void onComplete(Bundle values) 
        {
            saveCredentials(facebook);
            showToast( "Login Successfull in Facebook");
            //fetchFacebookFriends();
            //postToWall("Another post from Eclipse...");
             fetchMyFacebookStatuses();
            //fetchFriendsFacebookStatuses();    
        }

        @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 onCancel() 
        {
            // TODO Auto-generated method stub

        }

    }
    private void showToast(String message) 
    {
           Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }
}

以下是Log Cat:

04-02 12:16:58.691: A/chromium(16016): [FATAL:jni_android.cc(269)] Check failed: false. Please include Java exception stack in crash report
04-02 12:16:58.691: E/chromium(16016): ### WebView Version 40 (1808730-arm) (code 423501)
04-02 12:16:58.691: A/libc(16016): Fatal signal 6 (SIGABRT), code -6 in tid 16016 (facebooktesting)

1 个答案:

答案 0 :(得分:0)

你可以轻松地使用SocialAuth。 示例

下面

<强>初始化

初始化SocialAuth适配器对象并创建Facebook按钮。单击该按钮可授权适配器。

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

   adapter = new SocialAuthAdapter(new ResponseListener());

  facebook_button = (Button)findViewById(R.id.fb_btn);
  facebook_button.setBackgroundResource(R.drawable.facebook);

 facebook_button.setOnClickListener(new OnClickListener() 
 {
    public void onClick(View v) 
    {
        adapter.authorize(ProviderUI.this, Provider.FACEBOOK);
    }
});
}

在ResponseListener中接收身份验证响应并启动调用以获取各种功能。见下面的例子:

更新状态

通过调用adapter.updateStatus()来共享您的状态,并验证MessageListener中的响应。您可以使用任何语言在Facebook墙上分享您的状态。

private final class ResponseListener implements DialogListener 
{
   public void onComplete(Bundle values) {

  adapter.updateStatus(edit.getText().toString(), new MessageListener());                   
}
}

// To get status of message after authentication
private final class MessageListener implements SocialAuthListener {
@Override
public void onExecute(Integer t) {

Integer status = t;
if (status.intValue() == 200 || status.intValue() == 201 ||status.intValue() == 204)
 Toast.makeText(CustomUI.this, "Message posted",Toast.LENGTH_LONG).show();
else
Toast.makeText(CustomUI.this, "Message not posted",Toast.LENGTH_LONG).show();
}
}

更新故事

通过调用adapter.updateStory()来共享故事并验证MessageListener中的响应。您需要以下字段来共享故事:消息,标题,链接,图像。

private final class ResponseListener implements DialogListener 
{
public void onComplete(Bundle values) {

 adapter.updateStory(  "Hello SocialAuth Android" ,  "Google SDK for Android",
         "Build great social apps and get more installs.",
         "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated 
                                         Android apps.",  "https://www.facebook.com",               
                                        "http://carbonfreepress.gr/images/facebook.png", new MessageListener());                
}
}

// To get status of message after authentication
private final class MessageListener implements SocialAuthListener {
@Override
public void onExecute(Integer t) {

Integer status = t;
if (status.intValue() == 200 || status.intValue() == 201 ||status.intValue() == 204)
 Toast.makeText(CustomUI.this, "Message posted",Toast.LENGTH_LONG).show();

获取个人资料

通过getUserprofileAsync()方法获取用户配置文件,并在profileDataListener中接收响应。你可以得到

Facebook的用户个人资料ID,名字,姓氏,电子邮件,性别,国家/地区,语言,位置和个人资料图片网址。

 private final class ResponseListener implements DialogListener 
{
 public void onComplete(Bundle values) {

  adapter.getUserProfileAsync(new ProfileDataListener());                   
}
}

// To receive the profile response after authentication
private final class ProfileDataListener implements SocialAuthListener {

@Override
public void onExecute(Profile t) {

Log.d("Custom-UI", "Receiving Data");
Profile profileMap = t;
Log.d("Custom-UI",  "Validate ID         = " + profileMap.getValidatedId());
Log.d("Custom-UI",  "First Name          = " + profileMap.getFirstName());
Log.d("Custom-UI",  "Last Name           = " + profileMap.getLastName());
Log.d("Custom-UI",  "Email               = " + profileMap.getEmail());
Log.d("Custom-UI",  "Gender                   = " + profileMap.getGender());
 Log.d("Custom-UI",  "Country                  = " +              profileMap.getCountry());
 Log.d("Custom-UI",  "Language                 = " + profileMap.getLanguage());
Log.d("Custom-UI",  "Location                 = " + profileMap.getLocation());
Log.d("Custom-UI",  "Profile Image URL  = " + profileMap.getProfileImageURL());

获取联系人

通过getContactListAsync()方法获取用户联系人,并在contactDataListener中接收响应。您可以获取Facebook的名字,姓氏和个人资料网址。

private final class ResponseListener implements DialogListener 
{
public void onComplete(Bundle values) {

  adapter.getContactListAsync(new ContactDataListener());                   
}
}

// To receive the contacts response after authentication
private final class ContactDataListener implements SocialAuthListener> {

@Override
public void onExecute(List t) {

Log.d("Custom-UI", "Receiving Data");
List contactsList = t;
if (contactsList != null && contactsList.size() > 0) {
for (Contact c : contactsList) {
Log.d("Custom-UI", "Contact ID = " + c.getId());
Log.d("Custom-UI", "First Name = " + c.getFirstName());
Log.d("Custom-UI", "Last Name = " + c.getLastName());
 }
 }

获取用户Feed

通过getFeedListAsync()方法获取用户提要并在feedDataListener中接收响应。你可以得到

屏幕名称,消息,创建日期以及发布Feed的用户名称。

private final class ResponseListener implements DialogListener 
{
public void onComplete(Bundle values) {

 adapter.getFeedsAsync(new FeedDataListener());             
}
}

 // To receive the feed response after authentication
 private final class FeedDataListener implements SocialAuthListener> {

 @Override
 public void onExecute(List t) {

 Log.d("Share-Bar", "Receiving Data");

 List feedList = t;
 if (feedList != null && feedList.size() > 0) {
 for (Feed f : feedList) {
 Log.d("Custom-UI ", "Feed ID = " + f.getId());
 Log.d("Custom-UI", "Screen Name = " + f.getScreenName());
 Log.d("Custom-UI", "Message = " + f.getMessage());
 Log.d("Custom-UI ", "Get From = " + f.getFrom());
 Log.d("Custom-UI ", "Created at = " + f.getCreatedAt());
 }
  }                                    
}

获取相册

通过getAlbumsAsync()方法获取用户相册,并在albumDataListener中接收响应。你可以得到

相册名称,封面照片,照片数量,图片阵列及其名称和网址。

private final class ResponseListener implements DialogListener 
{
public void onComplete(Bundle values) {

 adapter.getAlbumsAsync(new AlbumDataListener());   
}
}

 // To receive the album response after authentication
 private final class AlbumDataListener implements SocialAuthListener> {

 @Override
 public void onExecute(List t) {

Log.d("Custom-UI", "Receiving Data");
List albumList = t;
if (albumList != null && albumList.size() > 0) {

// Get Photos inside Album
for (Album a : albumList) {
Log.d("Custom-UI", "Album ID = " + a.getId());
Log.d("Custom-UI", "Album Name = " + a.getName());
Log.d("Custom-UI", "Cover Photo = " + a.getCoverPhoto());
Log.d("Custom-UI", "Photos Count = " + a.getPhotosCount());

photosList = a.getPhotos();
if (photosList != null && photosList.size() > 0) {
for (Photo p : photosList) {
    Log.d("Custom-UI", "Photo ID = " + p.getId());
    Log.d("Custom-UI", "Name     = " + p.getTitle());
    Log.d("Custom-UI", "Thumb Image = " + p.getThumbImage());
    Log.d("Custom-UI", "Small Image = " + p.getSmallImage());
    Log.d("Custom-UI", "Medium Image = " + p.getMediumImage());
    Log.d("Custom-UI", "Large Image = " + p.getLargeImage());
   }}
  }}

上传图片

通过调用adapter.uploadimageAsync()来共享您的图像,并验证UploadImageListener中的响应。

 private final class ResponseListener implements DialogListener 
{
 public void onComplete(Bundle values) {

 adapter.uploadImageAsync("Landscape Images", "icon.png", bitmap, 0,new UploadImageListener());
 }
}

// To get status of image upload after authentication
private final class UploadImageListener implements SocialAuthListener {

@Override
public void onExecute(Integer t) {
Log.d("Custom-UI", "Uploading Data");
Integer status = t;
Log.d("Custom-UI", String.valueOf(status));
Toast.makeText(CustomUI.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
}
}

最后

 <strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px;">Conclusion</strong>

参考链接http://www.3pillarglobal.com/insights/part-1-using-socialauth-to-integrate-facebook-api-in-android