[Из песочницы] Пример использования Fabric (Twitter Kit) в Android Studio

8d1d7401d3b04c65a76c5c363684f5ef.pngВ конце октября прошлого года ребята из твиттера запустили Fabric. До сих пор информации о Fabric на русском языке в сети не было, поэтому я решил на примере объяснить, как все работает на примере авторизации, ленты твитов, добавлении твита и выходе из аккаунта.Для начала вам нужно получить сам Fabric. Для этого вам необходимо оставить здесь адрес почты. Письмо не заставит себя долго ждать, я получил платформу через часа два. После подтверждения вы попадаете на страницу с установкой плагина на вашу IDE.

Выбираем Android Studio, скачиваем плагин.

Установить его тоже очень просто: Preferences → Plugins → Install plugin from disk Ставим плагин, перезапускаем IDE и вуаля, у нас на панели инструментов появляется синий значок платформы, при клике на который появляется окно авторизации и выбора проекта, но мы создадим новый.

1. АвторизацияИтак, создаем проект. Снова вызываем окно фабрика, выбираем проект для него. Дальше нужно будет установить Twitter Kit (остальные нам пока неинтересны). Для авторизации в твиттере нам понадобиться выбрать в следующем окне третий вариант с авторизаций (Log in with Twitter). Зависимости, мета даты, твиттер кеи он подтянет сам. В следующих окнах он будет уже просить нас добавить несколько строк кода, ну мы же ему не сможем отказать? В итоге, наш стартовый xml будет иметь тольку кнопку логина:

activity_main.xml

В нашем активити тоже все просто:

MainActivity public class MainActivity extends ActionBarActivity {

private static final String TWITTER_KEY = «YOUR_TWITTER_KEY»; private static final String TWITTER_SECRET = «YOUR_TWITTER_SECRET»; private TwitterLoginButton loginButton;

@Override protected void onCreate (Bundle savedInstanceState) { super.onCreate (savedInstanceState); TwitterAuthConfig authConfig = new TwitterAuthConfig (TWITTER_KEY, TWITTER_SECRET); Fabric.with (this, new Twitter (authConfig)); setContentView (R.layout.activity_main);

loginButton = (TwitterLoginButton) findViewById (R.id.twitter_login_button); loginButton.setCallback (new Callback() { @Override public void success (Result result) { // Do something with result, which provides a TwitterSession for making API calls String name = result.data.getUserName (); Toast.makeText (MainActivity.this, «привет,» + name, Toast.LENGTH_SHORT).show (); }

@Override public void failure (TwitterException exception) { // Do something on failure } }); }

@Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { super.onActivityResult (requestCode, resultCode, data); loginButton.onActivityResult (requestCode, resultCode, data); }

@Override public boolean onCreateOptionsMenu (Menu menu) { getMenuInflater ().inflate (R.menu.menu_main, menu); return true; }

@Override public boolean onOptionsItemSelected (MenuItem item) { int id = item.getItemId ();

if (id == R.id.action_settings) { return true; }

return super.onOptionsItemSelected (item); }

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

@Override protected void onDestroy () { super.onDestroy (); } } Билдим, запускаем, пробуем авторизоваться, все работает. Просто? да!2. Лента твитов Создадим новое активити на базе ListActivity и будем использовать уже имеющий в инструментарии, адаптер.

TweetsFeedActivity public class TweetsActivity extends ListActivity { private TweetViewAdapter adapter;

@Override protected void onCreate (Bundle savedInstanceState) { super.onCreate (savedInstanceState); setContentView (R.layout.activity_list); adapter = new TweetViewAdapter (this); setListAdapter (adapter); loadTweets (); }

public void loadTweets () { final StatusesService service = Twitter.getInstance ().getApiClient ().getStatusesService ();

service.homeTimeline (null, null, null, null, null, null, null, new Callback>() { @Override public void success (Result> result) { adapter.setTweets (result.data); }

@Override public void failure (TwitterException error) { Toast.makeText (TweetsActivity.this, «Failed to retrieve timeline», Toast.LENGTH_SHORT).show (); } } ); } Что получилось.Отлично, идем дальше.

3. Пишем свой твит Идем в javadoc для этого метода и смотрим:

javadoc /** * Updates the authenticating user’s current status, also known as tweeting. *

* For each update attempt, the update text is compared with the authenticating user’s recent * tweets. Any attempt that would result in duplication will be blocked, resulting in a 403 * error. Therefore, a user cannot submit the same status twice in a row. *

* While not rate limited by the API a user is limited in the number of tweets they can create * at a time. If the number of updates posted by the user reaches the current allowed limit this * method will return an HTTP 403 error. * * @param status (required) The text of your status update, typically up to 140 characters. URL * encode as necessary. [node:840, title=«t.co link wrapping»] may effect character * counts. There are some special commands in this field to be aware of. For * instance, preceding a message with «D » or «M » and following it with a screen * name can create a direct message to that user if the relationship allows for * it. * @param inReplyToStatusId (optional) The ID of an existing status that the update is in reply * to. Note: This parameter will be ignored unless the author of the * tweet this parameter references is mentioned within the status text. * Therefore, you must include @username, where username is the author * of the referenced tweet, within the update. * @param possiblySensitive (optional) If you upload Tweet media that might be considered * sensitive content such as nudity, violence, or medical procedures, * you should set this value to true. See Media setting and best * practices for more context. Defaults to false. * @param latitude (optional) The latitude of the location this tweet refers to. This parameter * will be ignored unless it is inside the range -90.0 to +90.0 (North is * positive) inclusive. It will also be ignored if there isn’t a corresponding * long parameter. * @param longitude (optional) The longitude of the location this tweet refers to. The valid * ranges for longitude is -180.0 to +180.0 (East is positive) inclusive. This * parameter will be ignored if outside that range, if it is not a number, if * geo_enabled is disabled, or if there not a corresponding lat parameter. * @param placeId (optional) A place in the world. These IDs can be retrieved from [node:29]. * @param displayCoordinates (optional) Whether or not to put a pin on the exact coordinates a * tweet has been sent from. * @param trimUser (optional) When set to either true, t or 1, each tweet returned in a timeline * will include a user object including only the status authors numerical ID. * Omit this parameter to receive the complete user object. * @param cb The callback to invoke when the request completes. */ @FormUrlEncoded @POST (»/1.1/statuses/update.json») void update (@Field («status») String status, @Field («in_reply_to_status_id») Long inReplyToStatusId, @Field («possibly_sensitive») Boolean possiblySensitive, @Field («lat») Double latitude, @Field («long») Double longitude, @Field («place_id») String placeId, @Field («display_cooridnates») Boolean displayCoordinates, @Field («trim_user») Boolean trimUser, Callback cb); Видим, что единственный обязательный параметр — status. Окей, пишем метод: private void publishTweet () { final StatusesService statusesService = Twitter.getInstance ().getApiClient ().getStatusesService (); statusesService.update («Привет хабр!», null, null, null, null, null, null, null, new Callback() { @Override public void success (Result tweetResult) { Toast.makeText (TweetsActivity.this, «Успешно опубликовали статус», Toast.LENGTH_SHORT).show (); }

@Override public void failure (TwitterException e) { Toast.makeText (TweetsActivity.this, «Ошибка при отправке твита», Toast.LENGTH_SHORT).show (); } }); } Надо заметить, что в нынешней версии добавить к твиту фотографию нельзя. Придется подождать.4. Logout Просто добавим Twitter.getSessionManager ().clearActiveSession (); И он прервет текущую сессию.

Ссылка на репозиторий: github.com/afeozzz/fabric-testApp

Если сравнивать с тем, какие костыли приходились делать раньше даже с этими 4 функциями, то можно смело сделать вывод, что разработчики Fabric довольно сильно упростили жизнь разработчикам.

© Habrahabr.ru