Android使用已保存的accessToken

时间:2014-03-01 08:57:30

标签: php android facebook share

我想要使用保存在服务器中的DB中的accessToken进行共享的android应用程序 我可以与PHP共享该访问令牌:

try {
  $ret_obj = $facebook->api('/me/feed', 'POST',
  array(
  'link' => $link,
  'access_token' =>$data ,
  'message'=>$comment,
  'coordinates' => json_encode(array(
  'latitude'  => '1.3019399200902',
  'longitude' => '103.84067653695'))
  ));
  echo json_encode(array("message"=>1,"id"=>$ret_obj['id']));
} catch(FacebookApiException $e) {
  // If the user is logged out, you can have a 
  // user ID even though the access token is invalid.
  // In this case, we'll get an exception, so we'll
  // just ask the user to login again here.
  echo json_encode(array("message"=>2,"error"=>"access token is invalid"));
} 

是否可以直接从应用上传图片?!

由于

1 个答案:

答案 0 :(得分:0)

这包括Facebook共享存储在SharedPreferences中的access_token(您可以使用您的数据库)。但是access_token已经过期日期和时间(至少一旦你需要登录以避免过期)

public class ShareActivity extends Activity {
private ProgressDialog pDialog;
SharedPreferences prefs;

@SuppressLint("NewApi")
@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    pDialog = new ProgressDialog(this);
    pDialog.setMessage("loading");
    pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    pDialog.setCanceledOnTouchOutside(false);
    prefs = PreferenceManager.getDefaultSharedPreferences(ShareActivity.this);
    Log.d("accesstoken shared", prefs.getString(Strings.accesToken, ""));
    AccessToken at = AccessToken.createFromExistingAccessToken(prefs.getString(Strings.accesToken, ""), null, null, null, null);
    Session.openActiveSessionWithAccessToken(getApplicationContext(), at, new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            if (session.isOpened()) {
                Session.setActiveSession(session);
                publishFeedDialog(session);
                likePage();
            }
        }
    });

}

/**
 * 
 * @param session
 * 
 *            Sends the request to post the message as a feed.
 */
private void publishFeedDialog(Session session) {
    Bundle postParams = new Bundle();
    postParams.putString("message", getIntent().getStringExtra("message"));
    postParams.putString("access_token", session.getAccessToken());
    Request request = new Request(null, prefs.getString(Strings.pageID, "") + "/feed", postParams, HttpMethod.POST, callback);
    RequestAsyncTask newtask = new RequestAsyncTask(request);
    newtask.execute();

}

/**
 * 
 * Callback Listener for facebook post
 * 
 */
Request.Callback callback = new Request.Callback() {
    public void onCompleted(Response response) {
        FacebookRequestError error = response.getError();
        if (error != null) {
            Log.e("FACEBOOK ERROR", "" + error.getErrorMessage());
            pDialog.dismiss();
            Toast.makeText(ShareActivity.this, "Posting failed...", Toast.LENGTH_LONG).show();
            finish();

        } else {
            JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
            String postId = null;
            try {
                postId = graphResponse.getString("id");
                Log.d("post id", postId);
                pDialog.dismiss();
                Toast.makeText(ShareActivity.this, "Feedback Post successful", Toast.LENGTH_LONG).show();
                finish();
            } catch (JSONException e) {
                Log.d("Share Activity Json exception", e.getMessage(), e);
            }
        }
    }
};

/**
 * 
 * Likes the fb page
 * 
 */
private void likePage() {
    Bundle params = new Bundle();
    params.putString("object", "http://samples.ogp.me/" + prefs.getString(Strings.pageID, ""));
    Request nrequest = new Request(null, "me/og.likes", params, HttpMethod.POST);
    RequestAsyncTask task = new RequestAsyncTask(nrequest);
    task.execute();
    facebookLogout();
}

/**
 * 
 * This must be called if facebook api is used. Once the4 user is logged in,
 * the session is set here.
 * 
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);

}

/**
 * This will logout the user from Facebook
 */
public void facebookLogout() {
    Session session = Session.getActiveSession();
    if (session != null) {

        if (!session.isClosed()) {
            session.closeAndClearTokenInformation();

        }
    } else {

        session = new Session(this);
        Session.setActiveSession(session);
        session.closeAndClearTokenInformation();
    }
    AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
    Account[] accountsList = manager.getAccountsByType("com.facebook.auth.login");

    for (int i = 0; i < accountsList.length; i++) {
        manager.removeAccount(accountsList[i], null, null);
    }

}

@Override
protected void onStop() {
    super.onStop();
    pDialog.dismiss();
}

@Override
protected void onStart() {
    super.onStart();
    pDialog.show();
}
}