我在我的android應用程序中使用圖形api來連接到facebook.Now我正在做的是爲我的Facebook類創建一個實例,並且每次從主活動調用登錄方法。如果用戶使用應用程序登錄一次,並且當用戶打開應用程序下一次,就應該直接登錄使用以前活躍的Facebook session..How做到這一點?Sombody請幫助...如果用戶曾經登錄過,如何在android應用程序中向Facebook提供自動登錄?
登錄按鈕單擊方法
public void onBtnClicked(View v){
if(v.getId() == R.id.btnLogin)
{
FacebookClass na = new FacebookClass(this);
na.login();
}
}
這是我的登錄方法
public void login()
{
// start Facebook Login
Session.openActiveSession(mContext, true, new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
sessionState = true;
Toast.makeText(mContext, "Access token :" + session.getAccessToken() + "\n" +"Expires at "+session.getExpirationDate().toLocaleString(), Toast.LENGTH_LONG).show();
Log.i("sessionToken", session.getAccessToken());
Log.i("sessionTokenDueDate", session.getExpirationDate().toLocaleString());
access_token =session.getAccessToken();
pref = mContext.getPreferences(0);
edt = pref.edit();
Editor prefsEditor = pref.edit();
edt.putString("Access token", access_token);
edt.commit();
/**
* getting user's name and location
*/
// 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)
{
dispname = user.getName();
id = user.getId();
Object userLocation = user.getLocation();
Log.i("Profile information", ""+response);
String strLocation = (userLocation != null)? ((GraphObject) userLocation).getProperty("name").toString() : "No location found";
//location.setText("Lives in " + strLocation + "!");
disploc = strLocation;
edt.putString("Username", dispname);
edt.putString("Location", disploc);
edt.commit();
((MainActivity)mContext).dispatchInformations(dispname,disploc);
}
}
}).executeAsync();
/**
* Getting user's profile picture
*/
Bundle params = new Bundle();
params.putBoolean("redirect", false);
params.putString("type", "normal");
params.putString("height", "200");
params.putString("width", "200");
new Request(
Session.getActiveSession(),
"/me/picture",
params,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
/* handle the result */
Log.i("Profile pic", ""+response);
GraphObject graph=response.getGraphObject();
JSONObject jsonObj=graph.getInnerJSONObject();
JSONObject object;
String imageURL;
try {
object = jsonObj.getJSONObject("data");
imageURL=object.getString("url");
new DownloadImageTask().execute(imageURL);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
).executeAsync();
}
}
private boolean isSubsetOf(Collection<String> subset,
Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
});
}
在第一次登錄,在sharedpref設置。然後檢查您是否再次訪問SharedPref值是否可用。如果是的話,執行登錄Facebook的那個值.. – Riser 2014-12-04 07:26:34