How to Implement Android Annotations In Your App to Reduce Boilerplate Codes

0
Shares
How to Implement Android Annotations In Your App to Reduce Boilerplate Codes
Rate this post

Has it ever occurred to you?

You had to write common patterns such as setting click listeners, Facebook logins, request permission multiple times, which is not only a time consuming, but makes code structure more complex.

Well, with Android annotations, it’s possible to build an annotation processor to reduce the boilerplate codes.

Android annotations are a class of metadata that can be associated with classes, fields, methods, and even with more annotations. Basically, this metadata can be accessed at runtime via reflection, but you can access this metadata at build time with the help of android support annotations.

In this Android studio guide, we’ll see how to implement Android annotations to reduce boilerplate codes.

Let’s Get Started

Own Annotations

First job is to create your own annotations which will have different properties according to your requirement like If you want to method reference then

@Target(ElementType.METHOD)

If you want fields like butterknife do then

@Target(ElementType.FIELD)

Now annotation file will be something like below:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface FacebookInit {
boolean isDebugabble() default false;
}

If we pay more attention we can see @Target(ElementType.TYPE) this tells the compiler that this annotation can have multipurpose. If we have requirement like to define only on fields then we can have @Target(ElementType.FIELD)

There are various Element type which will be used in different cases for more info check Java Reflections.

If you want extra parameters like

@ViewById(R.id.buttonName)

The R.id.buttonName is what we called as property or fields of your annotations in above example I do have isDebugabble property which will be false by default.

If you do have multiple property then it will look like below:

@Target(ElementType.TYPE)<br/>
@Retention(RetentionPolicy.SOURCE)<br/>
public @interface FacebookLogin {<br/>
String[] permissions() default {"public_profile", "email"};<br/>
String[] fieldsFromGraph() default {"fields", "id, first_name, last_name, email,gender, location,picture.width(512)"};<br/>
}<br/>

Now that annotation created, we need to get the actions. by actions i mean when build.gradle starts before the java compiler starts we need to create our own class. as we can not alter the java class by apt-processor we need to create extra file for our code.

Annotation Processor Compile callback

let’s create annotation callback (by callback i mean at compile time this file will give you the references of the files which uses the our annotation).

@SupportedAnnotationTypes("com.parthdave.annotations.FacebookInit")
@SupportedSourceVersion(RELEASE_7)
public final class FacebookInitCodegen extends AbstractProcessor {

public final String TAG = "FacebookInitCodegen";
ErrorReporter mErrorReporter;
Types mTypeUtils;
@Override
public synchronized void init(ProcessingEnvironment processingEnvironment) {
super.init(processingEnvironment);
}

@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
....
}
}

Here @SupportedAnnotationTypes(“com.parthdave.annotations.FacebookInit”) this defines that when FacebookInit which is mine annotation if any files using this annotation please let me know here. and the classes which is using this annotation we will get it from process method.

Collection<? extends Element> facebookInitAnnotatedElements = roundEnvironment.getElementsAnnotatedWith(FacebookInit.class);

once we get the file we can process it. check FacebookLoginCodeGen.

Register this Annotation processor

image1

Goto main > resources > create directory META-INF.services now create file javax.annotation.processing.Processor

in which write reference path of your annotation processor like below:

com.[name].codegenerator.facebooklogin.FacebookLoginCodeGen

Now we can use our processor Use project or jar in your project any thing you like to have

I have used like this:

provided project(":annotationadapter")
apt project(":annotationprocessor")

And

@FacebookInit
public class ApplicationUtils extends Application {

public boolean isDebug = false;

@Override
public void onCreate() {
super.onCreate();
isDebug = true;
}
}

So generated java class looks like this:

public final class ApplicationUtils_ extends ApplicationUtils {
private int version;

public void onCreate() {
super.onCreate();
//Facebook Initialize
com.facebook.FacebookSdk.sdkInitialize(this);
com.facebook.FacebookSdk.setIsDebugEnabled(false);
}
}

Viola, We have created redundant code just by adding one annotation. So, what we can archive from this is like: Create services in background to get locations (BaseCode) Create Facebook,Gplus or any other logins from just annotation. RuntimePermissions like Permission Dispacher Pushnotifications GCM or FCM or Amazon Api calls failed popups etc.

Though, this implementation might see look difficult, but you can take help of top Android app development company to implement in your Android app.

Grab a free copy of Android Annotations Demo from Github.

 
0
Shares
 

Want to Develop Android App From Scratch? Contact Us Now

Get your free consultation now