我張貼下面的代碼,它進行登錄至Facebook,發佈到Facebook牆,呈現出輪廓影像,顯示好友列表和註銷....希望你會喜歡:)
// Add this code to your MainActivity
package com.example.abc;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.widget.Button;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
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;
import com.facebook.android.Util;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
// Your Facebook APP ID
private static String APP_ID = "your app id"; // Replace with your App
// ID
ArrayList<String> friends_list;
ListView lv;
// Instance of Facebook Class
public static Facebook facebook = new Facebook(APP_ID);
public static AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
public SharedPreferences mPrefs;
SharedPreferences.Editor editor;
public static String username;
// Buttons
static Button btnFbLogin;
static Button btnFbGetProfile;
static Button btnPostToWall;
static Button btnShowFriends;
static Button btnLogout;
ArrayAdapter<String> adapter;
ImageView user_picture;
URL img_value = null;
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_picture= (ImageView)findViewById(R.id.imageView1);
btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
btnShowFriends = (Button) findViewById(R.id.btn_show_friends);
btnLogout = (Button) findViewById(R.id.btn_logout);
mAsyncRunner = new AsyncFacebookRunner(facebook);
friends_list = new ArrayList<String>();
lv = (ListView) findViewById(R.id.list);
/**
* 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
* */
btnFbGetProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// getFriends();
getProfileInformation();
}
});
/**
* Getting Friends info
* */
btnShowFriends.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAsyncRunner
.request("me/friends", new FriendsRequestListener());
}
});
/**
* Posting to Facebook Wall
* */
btnPostToWall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
postToWall();
}
});
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// getFriends();
logoutFromFacebook();
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
/**
* 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);
btnFbLogin.setVisibility(View.INVISIBLE);
// Making get profile button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
btnShowFriends.setVisibility(View.VISIBLE);
// Making photos gallery button visible
btnLogout.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream", "user_photos", "friends_photos" },
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",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
// Making Login button invisible
btnFbLogin.setVisibility(View.INVISIBLE);
// Making logout Button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
btnShowFriends.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnLogout.setVisibility(View.VISIBLE);
getprofilepic();
}
@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() {
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);
// getting name of the user
username = profile.getString("username");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Name: " + username + "\nEmail: " + email,
Toast.LENGTH_LONG).show();
}
});
} 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();
}
public void logout() {
if (mPrefs != null) {
editor.remove("access_token");
editor.remove("access_expires");
editor.commit();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
private class FriendsRequestListener implements RequestListener {
String friendData;
// Method runs when request is complete
public void onComplete(String response, Object state) {
Log.v("", "FriendListRequestONComplete");
// Create a copy of the response so i can be read in the run()
// method.
friendData = response;
Log.v("friendData--", "" + friendData);
// Create method to run on UI thread
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
try {
// Parse JSON Data
JSONObject json;
json = Util.parseJson(friendData);
// Get the JSONArry from our response JSONObject
JSONArray friendArray = json.getJSONArray("data");
Log.v("friendArray--", "" + friendArray);
for (int i = 0; i < friendArray.length(); i++) {
JSONObject frnd_obj = friendArray.getJSONObject(i);
friends_list.add("Name:"+frnd_obj.getString("name") + " ID:"
+ frnd_obj.getString("id"));
}
adapter = new ArrayAdapter<String>(
getBaseContext(),
android.R.layout.simple_list_item_1,
android.R.id.text1, friends_list);
lv.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
@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
}
@Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
@SuppressWarnings("deprecation")
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
@Override
public void onComplete(final String response, Object state) {
Thread timer = new Thread() { //new thread
public void run() {
Boolean b = true;
try {
editor.remove("access_token");
editor.commit();
sleep(500);
Log.d("Logout from Facebook", response);
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
btnFbLogin.setVisibility(View.VISIBLE);
// making all remaining buttons invisible
btnFbGetProfile.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
btnShowFriends.setVisibility(View.INVISIBLE);
btnLogout.setVisibility(View.INVISIBLE);
adapter.clear();
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "You are logged out from Facebook", Toast.LENGTH_LONG).show();
}
});
while (b == true);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
}
};
};
timer.start();
}
@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) {
}
});
}
@SuppressWarnings("deprecation")
public void getprofilepic(){
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
final JSONObject profile = new JSONObject(json);
runOnUiThread(new Runnable() {
@Override
public void run() {
// getting name of the user
try {
username = profile.getString("username");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
img_value = new
URL("https://graph.facebook.com/"+username+"/picture?type=normal");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap mIcon1 = null;
try {
mIcon1 =
BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
user_picture.setImageBitmap(mIcon1);
}
});
} 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) {
}
});
}
}
//// 此代碼到activity_main.xml中
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn_fblogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Login with Facebook" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_fb_post_to_wall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Post to Wall"
android:visibility="gone" />
<Button
android:id="@+id/btn_get_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Get Profile Data"
android:visibility="gone" />
<Button
android:id="@+id/btn_show_friends"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Show Friends"
android:visibility="gone" />
<Button
android:id="@+id/btn_logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Logout"
android:visibility="gone" />
<ListView
android:id="@+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
///並添加Mainfest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.abc"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name="com.example.abc.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</application>
</manifest>
如果用戶在Facebook網站上更改密碼會怎麼樣? –
您需要使用[用戶訪問令牌](https://developers.facebook.com/docs/facebook-login/access-tokens/#usertokens)。短暫標記通常具有大約「小時」或'two',而長壽命的令牌通常具有大約60天的使用期限。使用Facebook移動SDK的移動應用獲得長壽命令牌 – Anirudha
Brontok:必須顯示密碼錯誤消息。 – user3349680