答案 0 :(得分:10)
看看TwitterAuthClient
。
示例用法类似于(其中getCallingActivity()可以替换为您的调用Activity
),
TwitterAuthClient twitterAuthClient = new TwitterAuthClient();
twitterAuthClient.authorize(getCallingActivity(), new Callback<TwitterSession>() {
@Override
public void success(final Result<TwitterSession> result) {
final TwitterSession sessionData = result.data;
// Do something with the returned TwitterSession (contains the user token and secret)
}
@Override
public void failure(final TwitterException e) {
// Do something on fail
}
});
然后将onActivityResult委派给TwitterAuthClient
,
twitterAuthClient.onActivityResult(requestCode, resultCode, data);
答案 1 :(得分:2)
您无需为此创建按钮。基本上,如果你深入研究一些类,你会发现代码相对简单。所以,我就是这样做的。您只需致电TwitterAuthClient().authorize(Activity, Callback<TwitterSession)
完整代码:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterAuthClient;
/**
* Created by Andrew on 6/23/15.
*/
public class ConnectTwitterActivity extends Activity {
//The auth client itself
/*you can abstract this and call TwitterCore.getInstance().login()
but basically that call is doing this one..
*/
TwitterAuthClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//instanciate our client
client = new TwitterAuthClient();
//make the call to login
client.authorize(this, new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
//feedback
Toast.makeText(getApplicationContext(), "Login worked", Toast.LENGTH_LONG).show();
}
@Override
public void failure(TwitterException e) {
//feedback
Toast.makeText(getApplicationContext(), "Login failed", Toast.LENGTH_LONG).show();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//this method call is necessary to get our callback to get called.
client.onActivityResult(requestCode, resultCode, data);
}
}
答案 2 :(得分:0)
您可能希望通过类似Twitter4J的方式调用常规的Twitter OAuth机制。如果您使用TwitterLoginButton,这些都是通过Twitter Kit中的功能为您完成的。
答案 3 :(得分:0)
如果您的目标是不在布局中添加TwitterLoginButton,请以编程方式创建TwitterLoginButton并手动执行单击事件:
TwitterLoginButton button = new TwitterLoginButton(this);
button.setCallback(new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
}
@Override
public void failure(TwitterException exception) {
// Do something on failure
}
});
button.performClick();
这里的关键点是,创建此按钮后,您可以在方便时致电button.performClick()
。