在应用程序的背景下发送推文

时间:2014-01-14 08:55:57

标签: java android social-networking tweets

我在网上搜索过。我找到了许多解决方案,以便发送推文,我得到了使用意图,它更好。

String tweetUrl = "https://twitter.com/intent/tweet?text=PUT TEXT HERE &url="+ "https://www.google.com";
Uri uri = Uri.parse(tweetUrl);
startActivity(new Intent(Intent.ACTION_VIEW, uri));

但我只是想在后台发送推文。如果有人这样做过,请与我分享。我的要求是在帖子发布到基于社交网络的应用程序时在后台发送推文。我可以在facebook的情况下这样做,但仍然在Twitter上苦苦挣扎。

以下是我为Twitter应用程序进行身份验证的代码: -

class twAsyn extends AsyncTask<String, Void, String>{
    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
         askOAuth();
        return null;  
    }

}

private void checkForSavedLogin() {  
     // Get Access Token and persist it  
     new accessUser().execute();
}  

class accessUser extends AsyncTask<String, Void, String>{

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
         AccessToken a = getAccessToken();  

            // storeAccessToken(a);
             loggedIUser.setTwSharing(true);
             if (a!=null) {

             // initialize Twitter4J  
             twitter = new TwitterFactory().getInstance();  
             twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);  
             twitter.setOAuthAccessToken(a);  
             ((TwitterApplication)getApplication()).setTwitter(twitter);  
             final User user;
             finish(); 
              }
        return null;
    }

}

private AccessToken getAccessToken() {
    SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
    String token = settings.getString("accessTokenToken", "");
    String tokenSecret = settings.getString("accessTokenSecret", "");
    if (token!=null && tokenSecret!=null && !"".equals(tokenSecret) && !"".equals(token)){
        return new AccessToken(token, tokenSecret);
    }
    return null;
}

private void getConsumerProvider() {
    OAuthProvider p = ((TwitterApplication)getApplication()).getProvider();
    if (p!=null){
        provider = p;
    }
    CommonsHttpOAuthConsumer c = ((TwitterApplication)getApplication()).getConsumer();
    if (c!=null){
        consumer = c;
    }
}



private void setConsumerProvider() {
    if (provider!=null){
        ((TwitterApplication)getApplication()).setProvider(provider);
    }
    if (consumer!=null){
        ((TwitterApplication)getApplication()).setConsumer(consumer);
    }
}


private void storeAccessToken(AccessToken a) {
    SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("accessTokenToken", a.getToken());
    editor.putString("accessTokenSecret", a.getTokenSecret());
    editor.commit();
}

@Override
protected void onResume() {
    super.onResume();
    System.out.println("RESUMING!!");
    if (this.getIntent()!=null && this.getIntent().getData()!=null){
        Uri uri = this.getIntent().getData();
        new twUserAcces(uri).execute();
    }
}

class twUserAcces extends AsyncTask<String, Void, String>{
    Uri uri;
    String verifier;
    public twUserAcces(Uri uri) {
        // TODO Auto-generated constructor stub
        this.uri = uri;
        if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
            verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);

        }
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        checkForSavedLogin();
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        try {


            // this will populate token and token_secret in consumer
            provider.retrieveAccessToken(consumer, verifier);

            // Get Access Token and persist it

            System.out.println(">>>>>>>> accesstoker "+consumer.getToken());
            System.out.println(">>>>>>>> accesstoker "+consumer.getTokenSecret());
            AccessToken a = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
            storeAccessToken(a);

            // initialize Twitter4J
            twitter = new TwitterFactory().getInstance();
            twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
            twitter.setOAuthAccessToken(a);
            ((TwitterApplication)getApplication()).setTwitter(twitter);
            Log.e("Login>>>>>>>>>>>>>>>>>>>>>.", "Twitter Initialised");


            User user = null;
            long h=twitter.getId();
            user = (User)twitter.getUserLists(0);

            finish();
        } catch (Exception e) {
            //Log.e(APP, e.getMessage());
            e.printStackTrace();
            System.out.println("e.getMessage()=="+e.getMessage());
            //Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }

        return null;
    }

}

private void askOAuth() {
    try {


        consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        provider = new CommonsHttpOAuthProvider("https://twitter.com/oauth/request_token", "https://twitter.com/oauth/access_token", "https://twitter.com/oauth/authorize");
        String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
        //Toast.makeText(this, "Please authorize this app!", Toast.LENGTH_LONG).show();
        setConsumerProvider();
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
    } catch (Exception e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

1 个答案:

答案 0 :(得分:0)

要在java中发送推文,您可以使用Twitter4J

创建Twitter应用程序:请参阅here

初始化您的对象:使用Twitter应用凭据填写凭据

ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
  .setOAuthConsumerKey("")
  .setOAuthConsumerSecret("")
  .setOAuthAccessToken("")
  .setOAuthAccessTokenSecret("");
TwitterFactory tf = new TwitterFactory(cb.build());

发送推文

Twitter twitter = TwitterFactory.getSingleton();
Status status = twitter.updateStatus(latestStatus);

有关最佳做法,请参阅here