Your SlideShare is downloading. ×
0
RoboGuice
RoboGuice
RoboGuice
RoboGuice
RoboGuice
RoboGuice
RoboGuice
RoboGuice
RoboGuice
RoboGuice
RoboGuice
RoboGuice
RoboGuice
RoboGuice
RoboGuice
RoboGuice
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

RoboGuice

1,155

Published on

Presentation about RoboGuice for Android.

Presentation about RoboGuice for Android.

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,155
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
16
Comments
0
Likes
2
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • OnActivityResultEventOnConfigurationChangedEventOnContentChangedEventOnContentViewAvailableEventOnCreateEventOnDestroyEventOnNewIntentEventOnPauseEventOnRestartEventOnResumeEventOnStartEventOnStopEvent
  • Transcript

    • 1. RoboGuice<br />well-known DI framework for Android<br />5/7/2011<br />1<br />Android May Days 2011<br />
    • 2. Dependency Injection<br />Устранение зависимостей в коде<br />Замена паттерна new()<br />Избавление от рутины создания фабрик, заводов и цехов<br />Возможность использования нескольких конфигураций<br />Ограничение кол-ва инстанций класса<br />Упрощение тестирования<br />5/7/2011<br />Android May Days<br />2<br />
    • 3. RoboGuice<br />http://code.google.com/p/roboguice/<br />Первым делом, это DI фрэймворк, который также позволяет:<br />@InjectView()<br />@InjectResource()<br />@InjectPreference()<br />@Inject System Services<br />@ObservesEvents<br />5/7/2011<br />I’m footer and nobody reads me<br />3<br />
    • 4. Injecting RoboGuice<br />СкачатьRoboGuice 1.1.1 и guice-2.0-no_aop.jar и подключить их к проекту. Или есть прекрасная возможность начать пользоваться Maven’ом <br /> (чего я еще не сделал)<br />Добавить в проект класс наследник RoboApplication и прописать его в AndroidManifest.xlmв тэге application значением параметра android:name (“.MyRoboApplication”)<br />5/7/2011<br />Damn footer live<br />4<br />
    • 5. Application Code Sample<br />5/7/2011<br />publicclassDiscoBoxApplicationextendsRoboApplication {<br />@Override<br />protectedvoidaddApplicationModules(List&lt;Module&gt; modules) {<br />modules.add(newNetSocketModule());<br />modules.add(newDiscoBoxModule());<br />super.addApplicationModules(modules);<br /> }<br />}<br />I’m a poop-poor footer, no one likes me<br />5<br />
    • 6. Modules<br />Происходит настройка bind-ингов классов на конкретные объекты<br />Статическая инициализация<br />5/7/2011<br />I could be a header<br />6<br />bind(Client.class).to(SocketClient.class);<br />@Providespublic Client provideClient() {<br /> Client c = newSocketClient();<br />requestInjection(c);<br />return c;<br />}<br />requestStaticInjection(ClientServiceAPI.class);<br />
    • 7. Module Sample<br />5/7/2011<br />footer sample<br />7<br />publicclassNetSocketModuleextendsAbstractModule {<br />publicstaticfinal String SERVER_BROADCAST_IN_PORT = &quot;SERVER_BROADCAST_IN_PORT&quot;;<br />publicstaticfinal String SERVER_BROADCAST_OUT_PORT = &quot;BROADCAST_OUT_PORT&quot;;<br />publicstaticfinal String SO_TIMEOUT = &quot;SO_TIMEOUT&quot;;<br />privatestaticfinalintSERVER_BROADCAST_IN_PORT_VALUE = 2012;<br />privatestaticfinalintSERVER_BROADCAST_OUT_PORT_VALUE = 2013;<br />privatestaticfinalintSO_TIMEOUT_VALUE = 20 * 1000;<br />@Override<br />protectedvoid configure() {<br /> bind(ProtocolProcessor.class).to(DefaultProtocolProcessor.class);<br /> bind(Connection.class).to(DefaultConnection.class);<br /> bind(Client.class).to(SocketClient.class);<br /> bind(Server.class).to(SocketServer.class).in(Scopes.SINGLETON);<br /> bind(ServerFinder.class).to(SocketServerFinder.class); <br /> bind(Integer.class).annotatedWith(Names.named(SO_TIMEOUT))<br /> .toInstance(SO_TIMEOUT_VALUE);<br /> bind(Integer.class).annotatedWith(Names.named(SERVER_BROADCAST_IN_PORT))<br /> .toInstance(SERVER_BROADCAST_IN_PORT_VALUE);<br /> bind(Integer.class).annotatedWith(Names.named(SERVER_BROADCAST_OUT_PORT))<br /> .toInstance(SERVER_BROADCAST_OUT_PORT_VALUE);<br /> }<br />}<br />
    • 8. Injecting<br />С помощью @Inject<br />C помощью Injector<br />5/7/2011<br />blah-blah-blah<br />8<br /> @Inject<br />protected Injector injector;<br />@Inject<br />publicSocketServer(@Named(NetSocketModule.SERVER_PORT) intport) {<br /> ...<br />}<br />@Inject<br />publicvoidsetProtocolProcessor(ProtocolProcessor processor) {<br />this.processor = processor;<br />}<br />Connection connection = injector.getInstance(Connection.class);<br />
    • 9. Lazy Injection<br />Использование интерфейса Provider&lt;T&gt;<br />5/7/2011<br />and lazy footer<br />9<br />@Injectpublic Provider&lt;Server&gt; serverProvider;<br />publicvoidmethodRequersServer() {<br /> Server servet = serverProvider.get();<br />...<br />}<br />
    • 10. Scopes<br />Можно пометить класс аннотацией @Singleton, для ограничения кол-ва инстанций тяжелого ресурсоемкого класса<br />5/7/2011<br />scopes looks like footer friends<br />10<br />@Singleton<br />publicclassSocketServerimplements Server {<br />...<br />}<br />
    • 11. Constructors with params<br />Использование аннотаций и специальных биндингов<br />5/7/2011<br />what footers are good for?<br />11<br />@Inject<br />publicSocketServer(@Named(NetSocketModule.SERVER_PORT) int port, <br />@Named(NetSocketModule.SERVER_BROADCAST_ADDRESS) String broadcastAddress,<br />@Named(NetSocketModule.SERVER_BROADCAST_IN_PORT) intbroadcastInPort,<br />@Named(NetSocketModule.SERVER_BROADCAST_OUT_PORT) intbroadcastOutPort) {<br />}<br />@Override<br />protectedvoid configure() {<br /> ...<br />bind(Integer.class).annotatedWith(Names.named(SERVER_BROADCAST_IN_PORT))<br /> .toInstance(SERVER_BROADCAST_IN_PORT_VALUE);<br />bind(Integer.class).annotatedWith(Names.named(SERVER_BROADCAST_OUT_PORT))<br /> .toInstance(SERVER_BROADCAST_OUT_PORT_VALUE);<br />bind(String.class).annotatedWith(Names.named(SERVER_BROADCAST_ADDRESS))<br /> .toInstance(SERVER_BROADCAST_ADDRESS_VALUE);<br />}<br />
    • 12. Constructors with params<br />Использование @Provides в модуле<br />5/7/2011<br />footer is watching you<br />12<br />@Provides Server provideServer() {<br /> Server server = newSocketServer(2011, &quot;224.0.0.0&quot;, 2013, 2014);<br />requestInjection(server);<br />return server;<br /> }<br />
    • 13. Events<br />Использовать уже готовые событий или написать свои<br />5/7/2011<br />footer, simple as is<br />13<br />publicvoidperformShutDown(@ObservesOnDestroyEvent event) {<br />doSomeCleanUp();<br /> }<br />@Inject protectedEventManagereventManager;<br />protectedvoid buy() {<br />eventManager.notify(MyOtherActivity.this, newMyBuyEvent() );<br /> }<br />protectedvoidhandleBuy(@ObservesMyBuyEventbuyEvent ) {<br />Toast.makeToast(this, &quot;You won&apos;t regret it!&quot;, Toast.LENGTH_LONG).show();<br /> } <br />//The event class can be anything you want<br />publicclassMyBuyEvent {<br /> ...<br />}<br />
    • 14. Views<br />Устранение лишнего,повторяющегося от активити к активити нудного тупого обезьяньего кодаfindViewById(R.id.damn_view_id) в onCreate()<br />5/7/2011<br />cool footer is not a crime<br />14<br />@InjectView(R.id.server_search_button_panel)ViewSwitchersearchButtonSwitcher;<br />@InjectView(R.id.server_selector)Spinner serverSelector;<br />@InjectView(R.id.server_search_button) Button searchButton;<br />@InjectView(R.id.client_music_mode_button) Button musicModuleButton;<br />
    • 15. Logging<br />RoboGuice&apos;sLn logger<br />Отличный формат вызова<br />Автоматическое отключение debug и verbose логов при release-ой сборке<br />В тэге лога сам пишет класс и номер строки кода<br />Можно легко переопределить формат отображения и перенаправить вывод лога в файл<br />5/7/2011<br />we footers hate each other<br />15<br />Ln.d(&quot;text&quot;);<br />Ln.d(&quot;formatted %s&quot;, &quot;text&quot;);<br />Ln.d(exception, &quot;reason %s&quot;, &quot;text&quot;);<br />
    • 16. Спасибо за внимание<br />Презентацию подготовил<br />Шауберт Александр shaubert.alexander@gmail.com<br /> Специально для Android May Days 2011<br />5/7/2011<br />and who will say thanks to footer<br />16<br />

    ×