在Facebook android sdk 文档中,给出的示例使用 Activity 对用户进行身份验证。是否可以从服务中做同样的事情?示例代码将非常方便。谢谢你
问问题
858 次
1 回答
0
除了 Activity 之外,不可能在 Facebook 对象中的任何其他地方进行授权。
您可以尝试通过一些网络服务获取访问令牌并初始化您的
Facebook facebook
接着就,随即。不过,您可以在活动中授权您的会话并通过活页夹传递它。
这是我的例子。
这是一项服务
public class ClientService extends Service {
//Facebook object to operate from service
private Facebook facebook;
...
private final ClientBinder clientBinter = new ClientBinder();
/** Binder to service */
public class ClientBinder extends Binder {
public ClientService getService() {
return ClientService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return clientBinter;
}
public void setFacebook(Facebook f) {
ClientService.this.facebook = f;
}
public boolean loggedFacebook() {
if (facebook == null)
return false;
return facebook.isSessionValid();
}
...
}
这是活动的用法
public class SomeActivity extends Activity{
private ClientService clientService;
private ServiceConnection clientConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
public void onServiceConnected(ComponentName name, IBinder service) {
ClientService.ClientBinder binder = (ClientService.ClientBinder) service;
clientService = binder.getService();
mBound = true;
if (facebook != null)
if (facebook.isSessionValid())
clientService.setFacebook(facebook);
}
};
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, ClientService.class);
bindService(intent, clientConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(clientConnection);
mBound = false;
}
}
.................
//And HERE IS MAGIC
.....
private void logINFacebook() {
if (facebook.isSessionValid())
return;
facebook.authorize(this,
getResources().getStringArray(R.array.facebookPermissions),
new DialogListener() {
public void onFacebookError(FacebookError e) {...}
public void onError(DialogError e) {...}
public void onComplete(Bundle values) {
if (mBound) {
clientService.setFacebook(facebook);
}
//Save to shared preferences(optional)
SharedPreferences.Editor editor = prefs.edit();
editor.putString(FACEBOOK_TOKEN_PREFNAME,
facebook.getAccessToken());
editor.putLong(FACEBOOK_EXPIRES_PREFNAME,
facebook.getAccessExpires());
editor.commit();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
facebook.authorizeCallback(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
}
于 2012-05-01T13:05:55.507 回答