如何在Twitter上发布推文使用自己的应用程序

时间:2014-01-13 05:04:47

标签: java android twitter

我想在Twitter上发布我的应用程序的推文。这条推文将在我的应用程序以及推特中显示。

我有用户的所有细节,我不想在Twitter上登录。以下是我从Web服务获取的格式:

<string xmlns="http://tempuri.org/">
    {"Id":"cc02cf6c-c143-4921-b5d6-6afec1243c10","TwitterUserId":"123456",
     "TwitterScreenName":"abc", "OAuthToken":"xxxxxxxxxxxxxxxxxxxx",
     "OAuthSecret":"xxxxxxxxxxxx", "UserId":"zzzzzzzzzz", "FollowersCount":1, "IsActive":true,
     "FollowingCount":13, "ProfileUrl":"", "ProfileImageUrl":"http://abs.xxxxxxxxxxxxx.png",
     "TwitterName":null}
</string>

下面是我在Twitter上发布推文的代码,但是他们在这里使用twitter登录。 我不想登录。

请指导我,如果可能的话,请提供一些示例代码。

我正在使用twitter4j库。

public class MainActivity extends Activity implements OnClickListener { 

    // Constants

    /**
     * Register your here app https://dev.twitter.com/apps/new and get your
     * consumer key and secret
     * */

    static String TWITTER_CONSUMER_KEY = "xxxxxxxxxxxxxxxxxx";
    static String TWITTER_CONSUMER_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";


    // Preference Constants
    static String PREFERENCE_NAME = "twitter_oauth";
    static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
    static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
    static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";

    static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";

    // Twitter oauth urls
    static final String URL_TWITTER_AUTH = "auth_url";
    static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
    static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

    Button btnLoginTwitter;
    Button btnUpdateStatus; // This is responsible for tweet updation
    Button btnLogoutTwitter;
    EditText txtUpdate;

    ProgressDialog pDialog;

    // Twitter
    private static Twitter twitter;
    private static RequestToken requestToken;

    // Shared Preferences
    private static SharedPreferences mSharedPreferences;

    // Alert Dialog Manager
    AlertDialogManager alert = new AlertDialogManager();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // Check if twitter keys are set
        if (TWITTER_CONSUMER_KEY.trim().length() == 0
                || TWITTER_CONSUMER_SECRET.trim().length() == 0) {
            // Internet Connection is not present
            alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens",
                    "Please set your twitter oauth tokens first!", false);
            // stop executing code by return
            return;
        }




    /*  
        RequestToken reqToken = (RequestToken) session.getAttribute(REQUEST_TOKEN);
        session.removeAttribute(REQUEST_TOKEN);

        if (!reqToken.getToken().equals(oauthToken)) {
                throw new TwitterException("Wrong oauth_token");
        }
        AccessToken token = twitter.getOAuthAccessToken(reqToken);
        */


        // All UI elements
        btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
        btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
        btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
        txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);

        // Shared Preferences
        mSharedPreferences = getApplicationContext().getSharedPreferences(
                "MyPref", 0);

        btnLoginTwitter.setOnClickListener(this);

        btnUpdateStatus.setOnClickListener(this);

        btnLogoutTwitter.setOnClickListener(this);

        /**
         * This if conditions is tested once is redirected from twitter page.
         * Parse the uri to get oAuth Verifier
         * */
        if (!isTwitterLoggedInAlready()) {
            Uri uri = getIntent().getData();
            if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
                // oAuth verifier
                String verifier = uri
                        .getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

                try {
                    // Get the access token
                    AccessToken accessToken = twitter.getOAuthAccessToken(
                            requestToken, verifier);

                    // Shared Preferences
                    Editor e = mSharedPreferences.edit();

                    // After getting access token, access token secret
                    // store them in application preferences
                    e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                    e.putString(PREF_KEY_OAUTH_SECRET,
                            accessToken.getTokenSecret());
                    // Store login status - true
                    e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                    e.commit(); // save changes


                    // Hide login button 
                    btnLoginTwitter.setVisibility(View.GONE);

                    // Show Update Twitter

                    txtUpdate.setVisibility(View.VISIBLE);
                    btnUpdateStatus.setVisibility(View.VISIBLE);
                    btnLogoutTwitter.setVisibility(View.VISIBLE);

                    // Getting user details from twitter
                    // For now i am getting his name only
                    long userID = accessToken.getUserId();

                    System.out.println("--------User Id--------------"+userID);
                    User user = twitter.showUser(userID);

                    System.out.println("-------- user --------------"+user);
                    String username = user.getName();

                    System.out.println("-------- username --------------"+username);

                    Toast.makeText(getApplicationContext(),
                            Html.fromHtml("<b>Benvenuto " + username + "</b>"),
                            Toast.LENGTH_LONG).show();

                } catch (Exception e) {
                    // Check log for login errors
                    Log.e("Errore Login", "> " + e.getMessage());
                }
            }
        }

    }

    /**
     * Function to login twitter
     * */




    private void loginToTwitter() {
        // Check if already logged in
        if (!isTwitterLoggedInAlready()) {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
            Configuration configuration = builder.build();

            TwitterFactory factory = new TwitterFactory(configuration);
            twitter = factory.getInstance();

            try {
                requestToken = twitter
                        .getOAuthRequestToken(TWITTER_CALLBACK_URL);

           System.out.println("requestToken"+requestToken);

                this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                        .parse(requestToken.getAuthenticationURL())));
            } catch (TwitterException e) {
                e.printStackTrace();
            }
        } else {
            // user already logged into twitter
            btnLoginTwitter.setVisibility(View.GONE);

            // Show Update Twitter

            txtUpdate.setVisibility(View.VISIBLE);
            btnUpdateStatus.setVisibility(View.VISIBLE);
            btnLogoutTwitter.setVisibility(View.VISIBLE);

            Toast.makeText(getApplicationContext(),
                    "Logged in", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Function to update status
     * */
    class updateTwitterStatus extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Update in corso...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting Places JSON
         * */
        protected String doInBackground(String... args) {
            Log.d("Tweet Text", "> " + args[0]);
            String status = args[0];
            try {
                ConfigurationBuilder builder = new ConfigurationBuilder();
                builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
                builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);

                // Access Token
                String access_token = mSharedPreferences.getString(
                        PREF_KEY_OAUTH_TOKEN, "xxxxxxxxxxxxxxxxxxxxxxxxxxx");
                System.out.println("access_token"+access_token);
                // Access Token Secret
                String access_token_secret = mSharedPreferences.getString(
                        PREF_KEY_OAUTH_SECRET, "xxxxxxxxxxxxxxxxxxxxxxxxxxx");

                System.out.println("access_token_secret"+access_token_secret);
                AccessToken accessToken = new AccessToken(access_token,
                        access_token_secret);
                Twitter twitter = new TwitterFactory(builder.build())
                        .getInstance(accessToken);

                // Update status
                twitter4j.Status response = twitter.updateStatus(status);

                Log.d("Status", "> " + response.getText());
            } catch (TwitterException e) {
                // Error in updating status
                Log.d("Twitter Update Error", e.getMessage());
            }
            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog and show
         * the data in UI Always use runOnUiThread(new Runnable()) to update UI
         * from background thread, otherwise you will get error
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Tweet Send", Toast.LENGTH_SHORT)
                            .show();
                    // Clearing EditText field
                    txtUpdate.setText("");
                }
            });
        }

    }

    /**
     * Function to logout from twitter It will just clear the application shared
     * preferences
     * */
    private void logoutFromTwitter() {
        // Clear the shared preferences
        Editor e = mSharedPreferences.edit();
        e.remove(PREF_KEY_OAUTH_TOKEN);
        e.remove(PREF_KEY_OAUTH_SECRET);
        e.remove(PREF_KEY_TWITTER_LOGIN);
        e.commit();

        // After this take the appropriate action
        // I am showing the hiding/showing buttons again
        // You might not needed this code
        btnLogoutTwitter.setVisibility(View.GONE);
        btnUpdateStatus.setVisibility(View.GONE);
        txtUpdate.setVisibility(View.GONE);

        btnLoginTwitter.setVisibility(View.VISIBLE);
    }

    /**
     * Check user already logged in your application using twitter Login flag is
     * fetched from Shared Preferences
     * */
    private boolean isTwitterLoggedInAlready() {
        // return twitter login status from Shared Preferences
        return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
    }

    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View view) {
        if (view == btnLoginTwitter) {
            loginToTwitter();
        }
        if (view == btnLogoutTwitter) {
            logoutFromTwitter();
        }
        if (view == btnUpdateStatus) {
            // Call update status function
            // Get the status from EditText
            String status = txtUpdate.getText().toString();

            System.out.println("----------hiiiiiiii--------------"+status);

            // Check for blank text
            if (status.trim().length() > 0) {
                // update status
                new updateTwitterStatus().execute(status);
            } else {
                // EditText is empty
                Toast.makeText(getApplicationContext(),
                        "Please enter status message", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

 ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
    configurationBuilder.setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
    configurationBuilder.setOAuthAccessToken("HERE ENTER UR ACCESS TOKEN RECEIVED IN YOUR WEB SERVICE"));
    configurationBuilder.setOAuthAccessTokenSecret("HERE ENTER UR ACCESS TOKEN SECRET RECEIVED IN YOUR WEB SERVICE"));
    Configuration configuration = configurationBuilder.build();
    final Twitter twitter = new TwitterFactory(configuration).getInstance();

    new Thread(new Runnable() {

            private double x;

            @Override
            public void run() {
                    boolean success = true;
                    try {
                            x = Math.random();
                            twitter.updateStatus(message +" "+x);
                    } catch (TwitterException e) {
                            e.printStackTrace();
                            success = false;
                    }

                    final boolean finalSuccess = success;

                    callingActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                    postResponse.onFinsihed(finalSuccess);
                            }
                    });

            }
    }).start(); 

如果您拥有有效的访问令牌和访问令牌密钥,则上述方法将允许您发布推文。 干杯:)

答案 1 :(得分:0)

以下是在Twitter上发布消息的代码

 ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
        configurationBuilder.setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
        configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));
        configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
        Configuration configuration = configurationBuilder.build();
        final Twitter twitter = new TwitterFactory(configuration).getInstance();

        new Thread(new Runnable() {

                private double x;

                @Override
                public void run() {
                        boolean success = true;
                        try {
                                x = Math.random();
                                twitter.updateStatus(message +" "+x);
                        } catch (TwitterException e) {
                                e.printStackTrace();
                                success = false;
                        }

                        final boolean finalSuccess = success;

                        callingActivity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                        postResponse.onFinsihed(finalSuccess);
                                }
                        });

                }
        }).start(); 

查看此tutorial了解详情。