Top Banner
Android Annotations Dale King
38

Android Annotations

Feb 23, 2016

Download

Documents

Jayme

Android Annotations. Dale King. Goal. Give an overview of AndroidAnnotations to whet your appetite I’ll touch on probably 90% of the annotations My goal is not to make you an expert on AndroidAnnotations , but just make you want to go try it and learn more. What are AndroidAnnotations?. - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Android Annotations

Android Annotations

Dale King

Page 2: Android Annotations

Goal

• Give an overview of AndroidAnnotations to whet your appetite

• I’ll touch on probably 90% of the annotations• My goal is not to make you an expert on

AndroidAnnotations, but just make you want to go try it and learn more.

Page 3: Android Annotations

What are AndroidAnnotations?

• AndroidAnnotations is an Open Source annotation processing library that speeds up Android development

• It takes care of the plumbing, and lets you concentrate on what's really important.

• By simplifying your code, it facilitates its maintenance."The ratio of time spent reading [code] versus writing is well over 10 to 1... making it easy to read makes it easier to write." - Robert C. Martin

Page 4: Android Annotations

What is Annotation Processing?

• Annotation Processing is a feature of the Java compiler that lets you write a library to process source code annotations at compile time

• Runs your annotation processing code in the compiler and can generate new source code files that will also be compiled

• There is no way with public API to modify existing classes

Page 5: Android Annotations

How does it work?

• AndroidAnnotations is a Java Annotation Processing Tool that generates Android specific source code based on annotations

• It enhances a class by subclassing it with a generated class that adds and overrides methods in the annotated class

• The generated class is named by appending an underscore to the name of the annotated class

Page 6: Android Annotations

How do you use it?

• APT is built into Sun javac so all you have to do is include Android Annotations jar in compile time class path

• In Eclipse it needs to be enabled for the project– There is a bug in the Eclipse compiler that causes

spurious errors if you import an APT generated class. So either access from same package or fully qualify

Page 7: Android Annotations

How do you use it?

• Everywhere in the project that you refer to an enhanced class you append an underscore to the class name:– In the Android Manifest– In layout resources– In the code

• The git repo has examples on setting up with maven + eclipse and gradle

Page 8: Android Annotations

Enhanced Component Annotations• Code generation begins with a class that is

annotated with one of the enhanced component annotations (which start with E)

@EActivity@EApplication@EBean@EFragment@EProvider

@EReceiver@EService@EView@EViewGroup

Page 9: Android Annotations

Layout Injection With@EActivity and @EFragment

public class MyListActivity extends ListActivity { @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); }

@EActivity(R.layout.main)public class MyListActivity extends ListActivity {

Page 10: Android Annotations

Fluent Intent Building Interface for EActivity and EService

Intent intent = new Intent(myContext, MyActivity.class);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TOP);startActivity(intent);

MyActivity_.intent(myContext).flags(Intent.FLAG_ACTIVITY_NEW_TOP).start();

Page 11: Android Annotations

View Injections

• For components with associated views you can have views automatically injected into fields

@EActivitypublic class MyActivity extends Activity {

// Injects R.id.myEditText@ViewById EditText myEditText;

@ViewById(R.id.myTextView)TextView textView;

Page 12: Android Annotations

Resource Injections

• Can have resources automatically injected into fields. 16 different annotations based on type:

@Eactivitypublic class MyActivity extends Activity {

@StringRes(R.string.hello)String myHelloString;

@IntegerRes int offset;

Page 13: Android Annotations

@EApplication and @App

• EApplication adds no new functionality to annotated application but let’s you automatically inject the application into any other enhanced component using @App annotation:

@EActivitypublic class MyActivity extends Activity {

@AppMyApplication application;

Page 14: Android Annotations

@EBean and @Bean

• EBean lets you enable enhancement for your own custom classes. Class must have one constructor that takes no parameters or a Context parameter.

• You can automatically inject new instances of a bean into any other enhanced component using @Bean annotation:

• Optionally EBean can be declared as a singleton

Page 15: Android Annotations

Injecting Beans@EActivitypublic class MyActivity extends Activity {

@BeanMyBean myEnhancedBean;

@Bean(MyImplementation.class)MyInterface myInterface;

Page 16: Android Annotations

@Extra

• @Extra lets you inject extra values from an intent into an EActivity

@EActivitypublic class MyActivity extends Activity {

@Extra("myStringExtra")String myMessage;

@Extra Date myDate = new Date();

Page 17: Android Annotations

Fragment Injection

• Lets you inject fragments by ID or by tag• Does not create them, must already be

created (e.g. in the layout)

@EActivity(R.layout.fragments)public class MyActivity extends FragmentActivity {

@FragmentById MyFragment myFragment; @FragmentByTag("myFragmentTag")

MyFragment myFragmentTag2;

Page 18: Android Annotations

Fragment Argument Injection

• Lets you inject arguments to a fragment into an enhanced fragment:

@EFragmentpublic class MyFragment extends Fragment {

@FragmentArg("myStringArgument")String myMessage;

@FragmentArg String anotherStringArgument;

Page 19: Android Annotations

System Service Injection

• Simplifies accessing system services from an activity:

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

@EActivitypublic class MyActivity extends Activity {

@SystemServiceNotificationManager notificationManager;

Page 20: Android Annotations

@AfterViews

• Method annotation for methods that are called after views are injected:

@EActivity(R.layout.main)public class MyActivity extends Activity {

@ViewById TextView myTextView;@AfterViews void updateTextWithDate() {

myTextView.setText("Date: " + new Date()); }

Page 21: Android Annotations

@AfterInject

• Method annotation for methods to be called when injection is complete for @Ebean

@EBean public class MyClass {@Bean MyOtherClass dependency;public MyClass() {

// dependency is null }@AfterInject public void doSomething () {

// dependency is set here }

Page 22: Android Annotations

Event Binding

• Method annotations for methods that are automatically called in response to UI events

@TextChange@AfterTextChange@BeforeTextChange@FocusChange@CheckedChange@Touch@Click@LongClick

@ItemClick@ItemLongClick@ItemSelect@OptionsItem@SeekBarProgressChange@SeekBarTouchStart@SeekBarTouchStop

Page 23: Android Annotations

Event Binding Examples@Click(R.id.myButton)void myButtonWasClicked() { [...] }

@Clickvoid anotherButton() { ... }

@Clickvoid yetAnotherButton(View clickedView) {

...}

Page 24: Android Annotations

@Background Annotation

• Method annotation that causes method to be executed on a background thread

void myMethod() {someBackgroundWork("hello", 42);

}@Background void someBackgroundWork(String aParam, long anotherParam) {

// … }

Page 25: Android Annotations

@Background parameters

• @Background(id="cancelable_task")– Allows job to be cancelled based on id

• @Background(serial = "test")– All background tasks with same serial value will

be executed sequentially• @Background(delay=2000)– Delay before starting task

Page 26: Android Annotations

@UIThread

• Method annotation that causes method to run on UI Thread (supports delay parameter):

void myMethod() {doInUiThread("hello", 42);

}

@UiThreadvoid doInUiThread(String aParam, long anotherParam){ // ...}

Page 27: Android Annotations

EActivity Modification annotations

• Annotations to add to an EActivity to modify its behavior

• @NoTitle– Shows activity with no title

• @FullScreen– Requests full screen

• @CustomTitle(R.layout.custom_title)– Use custom resource for title

Page 28: Android Annotations

Shared Preference Annotations

• Annotations to create a type-safe shared preference interface:

@SharedPrefpublic interface MyPrefs {

@DefaultString("John") String name();@DefaultInt(42) int age();long lastUpdated();

}

Page 29: Android Annotations

Injecting Shared Preference

• The @Pref annotation will inject a shared preference instance:

@EActivitypublic class MyActivity extends Activity {

@PrefMyPrefs_ myPrefs;

// ... }

Page 30: Android Annotations

Modifying Shared preferences

// Simple editmyPrefs.name().put("John");

// Batch editmyPrefs.edit() .name() .put("John")

.age() .put(42) .apply();

// Preference clearing:myPrefs.clear();

Page 31: Android Annotations

Reading Shared Preferences// Check if a value exists:boolean nameExists = myPrefs.name().exists();

// Reading a valuelong lastUpdated = myPrefs.lastUpdated().get();

// Reading a value and providing a defaultlong now = System.currentTimeMillis();long lastUpdated = myPrefs.lastUpdated().getOr(now);

Page 32: Android Annotations

Options Menu annotations@EActivity@OptionsMenu(R.menu.my_menu)public class MyActivity extends Activity {

@OptionMenuItemMenuItem menuSearch;

@OptionsItem(R.id.menuShare)void myMethod() {

// …}

Page 33: Android Annotations

Options Menu continued@OptionsItemvoid homeSelected() {

// The "Selected" keyword is optional }

@OptionsItem({R.id.menu_search, R.id.menu_delete})void multipleMenuItems() {}

@OptionsItem void menu_add(MenuItem item) { // You can add a MenuItem parameter

}

Page 34: Android Annotations

@InstanceState

• Field annotation to cause field to be saved and restored in instance state automatically

@Eactivitypublic class MyActivity extends Activity {

@InstanceStateint someId;

@InstanceStateMySerializableBean bean;

Page 35: Android Annotations

@OnActivityResult

• Method annotation to connect methods as callbacks for startActivityForResult

@OnActivityResult(REQUEST_CODE)void onResult(int resultCode, Intent data) { } @OnActivityResult(REQUEST_CODE)void onResult(int resultCode) { } @OnActivityResult(ANOTHER_REQUEST_CODE) void onResult(Intent data) { } @OnActivityResult(ANOTHER_REQUEST_CODE) void onResult() { }

Page 36: Android Annotations

Miscellaneous

• @OrmLiteDao – Field annotation for injecting OrmLite DAOs

• @RoboGuice – Combine Android Annotations with RoboGuice dependency injection without subclassing

• @Trace – Method annotation that logs entry and exit for the method

• @Transactional – Method annotation that executes method in a SQLite transaction

Page 37: Android Annotations

REST API

• Rest API lets you easily create REST clients using clean interfaces.

• It is a wrapper around the Spring Android RestTemplate Module.

Page 38: Android Annotations

Summary

• Android Annotations lets you reduce the amount of code to create an Android app

• Takes care of the boilerplate code for you.• The work is done at compile time so does not

slow app down (unlike RoboGuice)• https://github.com/excilys/androidannotations