我一直在寻找一种方法来发布我的Android应用程序的推文,但我找到的所有东西都不起作用。
我必须承认Twitter的API并不是那么容易理解,但我的代码并不长,而且我看不出我的错误在哪里。
这是我的代码:
public class PartagerTwitter extends Activity {
private CommonsHttpOAuthConsumer httpOauthConsumer;
private OAuthProvider httpOauthprovider;
public final static String consumerKey = XXX;
public final static String consumerSecret = XXX;
private final String CALLBACKURL = "myapp://twitactivity";
private Twitter twitter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
httpOauthprovider = new DefaultOAuthProvider("https://twitter.com/oauth/request_token",
"https://twitter.com/oauth/access_token",
"https://twitter.com/oauth/authorize");
String authUrl = httpOauthprovider.retrieveRequestToken(httpOauthConsumer, CALLBACKURL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Uri uri = intent.getData();
Log.i("test", uri.toString());
if (uri != null && uri.toString().startsWith(CALLBACKURL)) {
String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
try {
httpOauthprovider.retrieveAccessToken(httpOauthConsumer, verifier);
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(consumerKey, consumerSecret);
RequestToken requestToken = twitter.getOAuthRequestToken(CALLBACKURL);
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken);
String token = accessToken.getToken(),
secret = accessToken.getTokenSecret();
accessToken = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getOAuthAuthorizedInstance(consumerKey,consumerSecret,accessToken);
twitter.updateStatus("My First Status Update");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
当然,我的钥匙不是XXX。 另一个问题是,登录后是否有可能关闭Twitter窗口并将我的活动带到前台?
答案 0 :(得分:5)
请查看the following blog post以获取从Android应用发布到Twitter的完整端到端指南。
它还包含Github中正在运行的Android示例。
答案 1 :(得分:0)
在Twitter开发站点中创建具有读/写权限的应用程序,为您的应用程序生成访问令牌。
使用以下代码更新状态
public static void main(String[] args) {
String CONSUMER_KEY = "YOUR_CONSUMER_KEY";
String CONSUMER_SECRET = "YOUR_CONSUMER_SECRET";
String ACCESS_SECRET = "YOUR_ACCESS_SECRET";
String ACCESS_TOKEN = "YOUR_ACCESS_TOKEN";
// Consumer
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
// Access Token
AccessToken accessToken = null;
accessToken = new AccessToken(ACCESS_TOKEN, ACCESS_SECRET);
twitter.setOAuthAccessToken(accessToken);
// Posting Status
Status status = null;
try {
status = twitter.updateStatus("YOUR_STATUS");
} catch (TwitterException e) {
e.printStackTrace();
}
System.out.println("Successfully updated the status: "
+ status.getText());
}