Note: In the original article, Twitter4j3.0.3 is used. Due to the constant updates of official APIs, this version may be used incorrectly, as mentioned in the original article comment, nullpointerexception. I have tested the latest 4.0.1. I will attach the compressed package to the end of the article.
Certificate ------------------------------------------------------------------------------------------------------------------------------------------
Accessing social networks may make your applications look different. Today, I will share with you a demo of accessing Twitter in the Android app. In the demo, we use the oAuth protocol to allow users to authorize Twitter. If the authorization is successful, users can publish tweet through our demo. First, you have to register an application on Twitter, open https://dev.twitter.com/#, and create an application as shown in the following figure:
Since we will integrate Twitter into android apps, you can enter the callback URL as you like. Of course, your app homepage will be a good idea. Go to the settings page and change the permission to "Read, Write and Access direct messages". The specific path is "Application Type-> Access section ". These options must be activated so that messages can be directly published on your mobile phone. Please make sure that the setting has been successful, because I have set it three times and it cannot be hurt.
If you read my previous blog post "Google Cloud Messaging, ASP. NET Web Api and Android client", you will know that we need a key to complete a series of access tasks. Twitter works in a similar way. We also need a key, you know. Find your Consumer key and secret under applications> Details, and write it down. You will know what is going on later.
(Note: I saw the api key and api secret during the test. after entering the application you created, you can see the content under the api keys tab.
)
Okay, now everything is ready, and it's just a waste of money. You can encapsulate Twitter APIs into a Library, but to save time, I decided to use the open source Library http://twitter4j.org/en/#twitter4jto call twitterapi. Twitter4j is not an official Library, so be prepared.
With Twitter4J, you can easily integrate your Java application with the Twitter service.
Twitter4J is featuring:
? 100% Pure Java-works on any Java Platform version 5 or later
? Android platform and Google App Engine ready
? Zero dependency: No additional jars required
? Built-in OAuth support
? Out-of-the-box gzip support
? 100% Twitter API 1.1 compatible(From twitter4j.org)
Download and copy the Twitterrj-core-3.0.3.jar to the libs directory (TRANSLATOR: You need to introduce it to your buildpath, but visual eclipse can automatically help you deal with it ). We just want to publish a tweet, so the core Library is enough. If you have more requirements, see other jar packages of Twitter4j.
Our demo only has two simple activities, and MainActivity only has one button "Log in to Twitter"
The other is TwitterActivity, which is used to send Tweets.
In the main interface, when you start your app, the program will check your network availability (TRANSLATOR: Actually, you still need to access the Internet scientifically in China, you know ), check your consumer key and secret.
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); if (!OSUtil.IsNetworkAvailable(getApplicationContext())) { AlertMessageBox.Show(MainActivity.this, Internet connection, A valid internet connection can't be established, AlertMessageBox.AlertMessageBoxIcon.Info); return; } if (StringUtil.isNullOrWhitespace(ConstantValues.TWITTER_CONSUMER_KEY) || StringUtil.isNullOrWhitespace(ConstantValues.TWITTER_CONSUMER_SECRET)) { AlertMessageBox.Show(MainActivity.this, Twitter oAuth infos, Please set your twitter consumer key and consumer secret, AlertMessageBox.AlertMessageBoxIcon.Info); return; } initializeComponent();}You must also grant the following permissions:
If all the preceding checks are OK, you can see the "login with Twitter" button. When you click this button, the program will check whether the user has logged on to authorize. If yes, directly jump to TwitterActivity, and you can send a tweet; if not, sorry, Please authorize first. During authorization, the browser (or a page with the browser function) is started. the user logs on to the page for authorization and returns to TwitterActivity after the authorization is successful. You will know the following things.
The click listener of Login with Twitter looks like this:
private View.OnClickListener buttonLoginOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); if (!sharedPreferences.getBoolean(ConstantValues.PREFERENCE_TWITTER_IS_LOGGED_IN,false)) { new TwitterAuthenticateTask().execute(); } else { Intent intent = new Intent(MainActivity.this, TwitterActivity.class); startActivity(intent); } }};The above code first checks the internal settings of the Program (that is, Sharedpreferences). If PREFERENCE_TWITTER_IS_LOGGED_IN already has a value, the program has been authorized. If no authorization is set, the user must first grant permissions. In this process, TwitterAuthenticateTask () is executed ().
class TwitterAuthenticateTask extends AsyncTask
{ @Override protected void onPostExecute(RequestToken requestToken) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())); startActivity(intent); } @Override protected RequestToken doInBackground(String... params) { return TwitterUtil.getInstance().getRequestToken(); }}
TwitterAuthenticateTask creates a request token and obtains the address of the authorization page. Note that the intent construction of the Twitter authorization link requires an Action called Intent. ACTION_VIEW.
(For details about ACTION_VIEW, see Android api)
That is an activity action to display the data to the user. this is the most common action generated med on data-it is the generic action you can use on a piece of data to get the most reasonable thing to occur. for example, when used on a contacts entry it will view the entry; when used on a mailto: URI it will bring up a compose window filled with the information supplied by the URI; when used with a tel: URI it will invoke the dialer(From Google ).
In our program, the browser will process this request. (TRANSLATOR: in fact, we can implement a webview by ourselves, and then pass the url to this webview to complete this work .)
Click Authorize app. You will need to enter the user name and password. If the logon succeeds, Twitter will jump back to your app. If the logon fails, I'm sorry, an adult (haha, not in the original article ).
It looks very simple. But how is the request code generated, and how does Twitter know which Activity to jump? Next, let's look at the code. In TwitterUtil. class, you will see that I have completed all the work in singleton mode, such as setOAuthConsumerKey, setOAuthConsumerSecret, and getRequestToken...
public final class TwitterUtil { private RequestToken requestToken = null; private TwitterFactory twitterFactory = null; private Twitter twitter; public TwitterUtil() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(ConstantValues.TWITTER_CONSUMER_KEY); configurationBuilder.setOAuthConsumerSecret(ConstantValues.TWITTER_CONSUMER_SECRET); Configuration configuration = configurationBuilder.build(); twitterFactory = new TwitterFactory(configuration); twitter = twitterFactory.getInstance(); } public TwitterFactory getTwitterFactory() { return twitterFactory; } public void setTwitterFactory(AccessToken accessToken) { twitter = twitterFactory.getInstance(accessToken); } public Twitter getTwitter() { return twitter; } public RequestToken getRequestToken() { if (requestToken == null) { try { requestToken = twitterFactory.getInstance().getOAuthRequestToken(ConstantValues.TWITTER_CALLBACK_URL); } catch (TwitterException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } return requestToken; } static TwitterUtil instance = new TwitterUtil(); public static TwitterUtil getInstance() { return instance; } public void reset() { instance = new TwitterUtil(); }}This class is the only place where you need to set the Consumer Key and Consumer Secret. Callback URL is also required, because Twitter redirects to the specified Activity after successful authentication. In my demo, I want to jump to TwitterActivity, so the value of TWITTER_CALLBACK_URL is like this:
public static String TWITTER_CALLBACK_URL = oauth://com.hintdesk.Twitter_oAuth;
This seems to have nothing to do with TwitterActivity. Right. The job is not finished yet. In AndroidManifest. xml:
We claim that TwitterActivity can be invoked by the browser in the format of "oauth: // com. hintdesk. Twitter_oAuth. So after the authentication is successful, you will all know about the future. After TwitterActivity is aroused, you can't wait to send a tweet. Er, don't worry, continue to work ---- but just stick to it. After TwitterActivity is started, you can get the access token from intent and then send a tweet message.
private void initControl() { Uri uri = getIntent().getData(); if (uri != null && uri.toString().startsWith(ConstantValues.TWITTER_CALLBACK_URL)) { String verifier = uri.getQueryParameter(ConstantValues.URL_PARAMETER_TWITTER_OAUTH_VERIFIER); new TwitterGetAccessTokenTask().execute(verifier); } else new TwitterGetAccessTokenTask().execute();}If you have access token, make sure you start to send a tweet message:
if (!StringUtil.isNullOrWhitespace(accessTokenString) && !StringUtil.isNullOrWhitespace(accessTokenSecret)) { AccessToken accessToken = new AccessToken(accessTokenString, accessTokenSecret); twitter4j.Status status = TwitterUtil.getInstance().getTwitterFactory().getInstance(accessToken).updateStatus(params[0]); return true;}This access token can be used only after the Twitter authorization is successful and jumps to our app. However, once you get this access token, you can store it and keep using it without any authorization.
try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, params[0]); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(ConstantValues.PREFERENCE_TWITTER_OAUTH_TOKEN, accessToken.getToken()); editor.putString(ConstantValues.PREFERENCE_TWITTER_OAUTH_TOKEN_SECRET, accessToken.getTokenSecret()); editor.putBoolean(ConstantValues.PREFERENCE_TWITTER_IS_LOGGED_IN, true); editor.commit(); return twitter.showUser(accessToken.getUserId()).getName();} catch (TwitterException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.}Params [0] is the value of "oauth_verifier. You can see in the initControl function provided previously.
Yes, it's perfect.
We hope this demo can help your application access Twitter and expand more and more functions.
Source Code: "Connect to Twitter in Android Phone"
Certificate ------------------------------------------------------------------------------------------------------------------------------------
Wow, the translation is over. Since the translation of science and technology news last year, I have never done this kind of thing. I do not enjoy the translation process, but I think it is necessary to share a good article with you.
In addition, since the original text of Twitter4j3.0.3 seems outdated, So I attached my 4.0.1: http://pan.baidu.com/s/1o6jVXGm
Or to Twitter4j official site: http://twitter4j.org/en/index.html (need scientific Internet OH ~)