How to Use JRebel for Android

Android development is great so long as your project stays relatively small. As the functionality of your project grows you’ll find that your build times follow suit. This puts you in the position where you spend most of your time figuring how to make your build run faster rather than adding more value to your actual app.

You can also check : Why and How to use JRebel in Java

The interwebs are packed full with suggestions of how to squeeze the most out of your Gradle builds. There are some great posts on this, including, “Making Gradle builds faster”. Although you can win back seconds and maybe even minutes, yet some bottlenecks will still remain in your build. For example having annotation based dependency injections are nice to have for a cleaner architecture, but it has an impact on your build time.

One thing you can try is JRebel for Android. It takes a different approach by not introducing a new apk after each change. Instead apk gets installed once and delta packages are shipped over to the device or emulator and are applied during runtime. This logic is nothing new and has been present in the Java EE/SE with JRebel for more than 8 years.

Let’s take the Google IO 2015 app and see how the JRebel for Android setup works as well as how it can save you valuable time.

Installing JRebel for Android

JRebel for Android is available as a plugin for Android Studio. You can download it directly from the IDE by navigating to Plugins > Browse Repositories and searching for “JRebel for Android”.


If for some reason you can’t access the public maven repositories you can download it directly from the JetBrains homepage. After which you need to install via the Plugins > Install plugin from disk… route.

Once the plugin is installed, you’ll need to restart Android Studio, as usual after a plugin installation. After restart, you need to provide your name and email to get your free 21 day trial of JRebel for Android.

Running my application with JRebel for Android

Now the plugin is installed, you just need to click the Run with JRebel for Android button, which will always build a new apk if changes are detected between the previous installation. Run with JRebel for Android is the same as the Run action in Android Studio. So you’ll be faced with the same run flow, where you first need to pick a device and then apk is built and installed on that device etc.



To update your code and resources, JRebel for Android needs to process the project’s classes and embed an agent to the application. JRebel for Android will only run with a debuggable flavor, so your release apk is never affected. In addition no changes are required to your project. For a detailed overview of how JRebel for Android works, read this under the hood post.
So pressing Run with JRebel for Android on the Google IO 2015 application would result in the following:

Applying changes with JRebel for Android

The Apply changes button is the key when using JRebel for Android, it will do the least amount of work possible to make your changes and updates visible on your device. If you didn’t use Run with JRebel for Android to install the application yet, Apply changes will take care of the installation on your behalf.

Now let’s make a simple functional change to the application. For each session taking present in GoogleIO you can send feedback. We’ll add one additional element to the question, an input for your name and we’ll use the value from that input in a Toast thanking you for providing feedback.

Step 1: Add an EditText component to the session_feedback_fragment.xml

<FrameLayout    
 android:layout_width="match_parent"    
 android:layout_height="wrap_content">    
 <EditText    
 android:id="@+id/name_input"    
 android:layout_width="match_parent"    
 android:layout_height="wrap_content"/>    
</FrameLayout>


Step 2: Fix the paddings

<FrameLayout    
 android:layout_width="match_parent"    
 android:layout_height="wrap_content"    
 android:paddingLeft="@dimen/padding_normal"    
 android:paddingStart="@dimen/padding_normal"    
 android:paddingRight="@dimen/padding_normal"    
 android:paddingEnd="@dimen/padding_normal"    
 android:paddingTop="@dimen/spacing_micro"    
 android:paddingBottom="@dimen/padding_normal">


Step 3: Add a hint

<EditText    
 android:id="@+id/name_input"    
 android:layout_width="match_parent"    
 android:layout_height="wrap_content"    
 android:hint="@string/name_hint"/>


During all of these changes we have remained on the same screen on our device throughout. After each Apply change Activity.recreate() is invoked by JRebel for Android. So your top most activity will go through the same callbacks as you would if you rotated your device from portrait to landscape, for example.
So far we’ve only performed resource changes, so let’s change some Java code as well.

Step 4: Show a toast in SessionFeedbackFragment.sumbitFeedback()

EditText nameInput = (EditText) getView().findViewById(R.id.name_input);
Toast.makeText(getActivity(), "Thanks for the feedback " + nameInput.getEditableText().toString(), Toast.LENGTH_SHORT).show();

Application restart vs Activity restart

Not all changes will trigger an Activity.recreate() invocation. Should you change something in the AndroidManifest, a new apk has to be built and an incremental install will be performed. In this case the application will be restarted. Application restart will also be done if you replace a superclass or change interfaces that the class is implementing. Here is a full breakdown of activity vs application restart:
Activity restartApplication restart
Adding, removing, modifying methodsAdding, removing implemented interfaces
Adding, removing, modifying constructorsReplacing superclasses
Adding, removing fields
Adding, removing classes
Adding, removing annotations
Adding, removing, modifying static fields value
Adding, removing enum values
Modifying interface
Adding, removing, modifying XML resources

Why should you try JRebel for Android?

There are loads of reasons! Here are some of the most persuasive reasons as to why you should give it a go:

  1. Reduce the time it takes to see your changes on the device
  2. Polishing UI and getting that pixel perfect result no longer takes hours because of long build times
  3. No need to change anything in your project to make JRebel for Android work
  4. Use debugger and update code and resources at the same time! That’s right JRebel for Android comes with full debugger support!

Why and How to use JRebel in Java

First of all you should know about what is JRebel and why you should use it with your Java program. This post reviews some of the great advantages of using JRebel in Java development, and how eradicating the daily, time-consuming process of redeploying your application to see your changes has long-lasting effects on the way that you will write code in the future.

What is JRebel ?

According to their website -
"JRebel is an anything-Java plugin that speeds up JVM-based development (Java, Scala, Groovy) by reloading changes made in your workspace into a running JVM, without restarts or redeploys, maintaining the state of the application while you’re coding."
Don't worry if you're Android Dev : How to Use JRebel for Android

What would you rather be doing?


According to above image you can easily find that when you make a Java web application then whenever you change in your Java code you need to build, deploy and then run your changes which take some crucial time. But when you use JRebel then it save your time to build and deploy. Now you just change your Java code and test your program instead of build and deploy your application.

How to add JRebel in your IDE(Eclipse, MyEclipse, Netbeans etc.) 

  1. Firstly go to JRebel website.
  2. Then follow the instruction which are given in above link.
  3. Activate your JRebel plugin. 
  4. After activating right click on your project in IDE and find JRebel option.
  5. Add JRebel in that project which create rebel.xml in WEB-INF/classes.
  6. Thats it. Change your code and run the program.

Demo :



Why you use JRebel ?

Advantage #1: See all changes immediately

Does your code smell? Find out really quickly and run your own mini-tests throughout the day. Remove bad code before it goes to QA and they make fun of you.

With JRebel, you get to see the your changes immediately after compiling them. When the IDE builds classes automatically, the process is as fast as using a scripting language or testing your latest HTML changes. In fact, I urge you to try compiling the following code snippet, start it up with JRebel enabled, and change the “Hello World” part to something else while the program is running. 
public class TestLoop {
    public static void main(String... args) throws Exception {
        while (true) {
            saySomething();
            Thread.sleep(1000);
        }
    }
    private static void saySomething() {
        System.out.println("Hello World");
    }
}
For me, the console output following the JRebel banner was (yes, I write fast):

Hello World
Hello World
Hello World
JRebel: Reloading class 'TestLoop'.
Goodbye Redeploys
Goodbye Redeploys

This opens up a world of possibilities that have never before been available for developers. It combines the power of Java with the fast turnaround of dynamic scripting languages. You don’t have to queue up gazillion changes before redeploying. You can code by making small incremental changes and alt-tabbing to your browser to verify the results.

Advantage #2: Fine-tuning through incremental changes

This works best when you have to implement some logic that is tricky to get just right. Imagine you have to add validation to your form. With JRebel, you can add the rules field by field and play around with the way errors should be displayed until satisfied by the results. You may want to add some new fields to your controller or validator. That is supported, too. By the way, JRebel preserves all application state, which means it does not matter how you reached the page you’re modifying.

JRebel actually goes way beyond “simple” class reloading. Applications today take advantage of frameworks and JEE technologies, such as EJBs, Hibernate, Spring Framework, JSF, Seam, Struts, etc. The thing with those frameworks and technology implementations is that they initialize themselves when the application starts up and generate lots of metadata. It is usually a good thing since nobody wants Hibernate to re-initialize itself for every HTTP request (that’s what PHP programs have to do, by the way, even with opcode caching enabled).

JRebel has addressed this by having explicit support for almost 60 popular frameworks and application containers. This means when you make a change to a “special” resource such as adding a new EJB, changing JPA mappings (either via xml or annotations), or add new Spring Beans (again, either via xml or annotations), JRebel updates the metadata to reflect those changes. Your job is to press F5 in the browser.

Advantage #3: Debug remotely for fun and profit

JRebel makes remote debugging more useful than ever. Imagine you are using it to hunt down some difficult bug. Now you can hit a breakpoint, investigate what’s going on, make a change, resume execution, and see the result almost immediately!

The new code kicks in right after compiling the code, next time when the affected method is invoked. You can use this approach to fix discovered bugs immediately or to quickly add some debugging statements in the code (just remember to avoid committing them). You can even drop to a parent frame and check the effect immediately!

Advantage #4: Explore the code with ease

One of the benefits of small turnaround is that you can test the framework features interactively. You can write a small method to test some functionality of a new framework and learn hands-on how it works. Python and Scala even have interactive shells.

The problem here is the applicability in real world. While exploring the API of Java libraries is easy (even if they lack documentation), it can be ridiculously tedious in some other languages, especially when they are dynamic in nature, lack documentation, and/or miss out on good IDE support.

Even if you can indeed enjoy the fast turnaround with PHP and the like, it has little net value when you have to dig into some big and obscure framework (like Joomla CMS, which I actually tried that a few years ago, and it wasn’t pleasant) to see how it works. The ability to ctrl-click and dive into the code, as well as enjoy the auto-completion would be great, if only they were there. Granted, there is some support for it in modern IDEs, but it is nowhere nearly as useful. The difference is in the order of magnitudes.

Java, on the other hand, suffers from the fact that while the 3rd-party code is easily navigable, writing the stubs and running them can be tedious or time consuming. Writing stand-alone tests requires effort to set up and are not exactly a substitute for a real-world use case.

Embedding a test code into an existing application is simple and easy, but restarting the server or redeploying the app to see the changes takes time...unless you’re using JRebel to eliminate the need to restart.

Advantage #5: Deploying code locally or remotely

It’s great when a developer can check out code from a repository, compile it, and deploy the thing in his own machine. Sometimes this is not possible due to performance reasons, or the whole system is simply too complex. Sometimes the system has to run in a different network than the developer’s, which cannot be easily simulated. Some developers may be using low-powered laptops. Whatever the reason, sometimes running the app in the same machine is not an option.

I can almost hear developers cry (myself included) when that is the case. JRebel can help even in this case and the capability to make a system deployable on a developer’s machine is not crucial anymore.

JRebel Remoting (beta) was introduced from version 4.6, which lets you push changes from a developer’s machine to a remote server. It works over HTTP on the same port as the server is serving the application itself, therefore needs close to zero configuration to set up and no changes to firewall settings. In the screencast, we show JRebel Remoting in action when deploying to Amazon EC2, so if it can work well in the cloud far away, it will definitely work in your LAN or on the other side of the city.

You can even let multiple developers loose on a single application instance on a remote machine (but not simultaneously). By default, JRebel Remoting reverts back to the initial codebase when the app server is restarted. You can set up an application on the remote machine, have a developer have his way with it, restart it (ok, there’s one redeploy, sorry), and allow another developer do his magic on the app. This is the case when both developers are making changes to the same application. When there are several apps deployed to the remote server, developers can bombard them without stepping on each other’s toes.

Advantage #6: No restarts = More time for better stuff

No restarts means no forced interruptions, which means devs have more time for doing better things. Sometimes it’s hard to maintain concentration on a single task for more than a few minutes, and that’s when the level of focus is totally up to me. If there was a circus clown jumping out from behind a door every 6 minutes to frighten me, I couldn’t imagine working properly throughout the day.

With JRebel, you get more time to meet your deadlines, research & learn and *gasp* communicate with people. According to a recent report on Developer Stress, it came out that developers really do care about making deadlines and their level of expertise, wishing they had more time to spend on education. We also discovered that for every 1 hour developers spend writing code, they spend 30 minutes dealing with communication overhead (i.e., meetings, chats, reporting/timesheets, etc.). JRebel’s instantly class reloading magic simply frees up more time for doing the things that developers are already spending time on. The 2012 Developer Productivity Report is FREE and packed with Java stats, analysis and interviews. Inside you’ll find expanded coverage on technologies and tools used by Java development teams along with analysis and interviews with Java experts on “What makes developers tick?

Final words

JRebel will give you the best of both worlds—the performance, scalability and robustness of Java, as well as the FTL-turnaround and the feeling of lightness, which are typically associated with 100-line guestbook applications, not with big mature systems. JRebel behaves as if it’s in Rome—you don’t have to make changes to your code, architecture or sysops. It adapts to your environment and requirements. All you have to do is start using it. You get to keep all the effort and investments already made to your infrastructure.

Add Notification Badge in Android

Notification Badge is a simple feature, but it’s hugely useful because it lets you know exactly which apps need your attention, and how much attention they need.

For some reason, Google has yet to create a similar badge system in Android. Instead, notifications are collected in the notification panel, so users don’t know how many notifications they have from each app until they swipe open the panel and look.
Alternative : Make Badge(Item count) in Android
Today i am telling you about a library which can help to create notification badge with animation.

add notification badge in android

Gradle

compile 'com.nex3z:notification-badge:0.1.0'

Usage

Use setNumber(int number) or setText(String text) to add number or arbitrary text on the badge. Use clear() to clear the badge.

Downlaod library

First of all you need to define that badge in

AndroidManifest.xml

<application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 android:supportsRtl="true"
 android:theme="@style/AppTheme">
 <activity android:name=".MainActivity">
  <intent-filter>
   <action android:name="android.intent.action.MAIN"/>

   <category android:name="android.intent.category.LAUNCHER"/>
  </intent-filter>
 </activity>
</application>
Now create a layout where i notify the action and for this demo i am creating three button -->> Increase, Many Notification and Clear

activity_main.xml

<ImageView
 android:id="@+id/icon"
 android:layout_width="48dp"
 android:layout_height="48dp"
 android:layout_marginTop="8dp"
 android:src="@drawable/ic_chat_24dp"/>

<com.nex3z.notificationbadge.NotificationBadge
 android:id="@+id/badge"
 android:layout_width="28dp"
 android:layout_height="28dp"
 android:layout_toRightOf="@id/icon"
 android:layout_alignTop="@id/icon"
 android:layout_marginLeft="-16dp"
 android:layout_marginTop="-8dp"
 app:badgeBackground="@drawable/badge_bg_with_shadow"
 app:maxTextLength="2"/>

<Button
 android:id="@+id/increase"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_below="@id/icon"
 android:text="@string/increase"/>

<Button
 android:id="@+id/many"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_below="@id/increase"
 android:text="@string/many"/>

<Button
 android:id="@+id/clear"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_below="@id/many"
 android:text="@string/clear"/>
And finally this time to perform action by

MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.nex3z.notificationbadge.NotificationBadge;

public class MainActivity extends AppCompatActivity {

    NotificationBadge mBadge;
    private int mCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBadge = (NotificationBadge) findViewById(R.id.badge);

        Button increase = (Button) findViewById(R.id.increase);
        increase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBadge.setNumber(++mCount);
            }
        });

        Button many = (Button) findViewById(R.id.many);
        many.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCount = 98;
                mBadge.setNumber(mCount);
            }
        });

        Button clear = (Button) findViewById(R.id.clear);
        clear .setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCount = 0;
                mBadge.setNumber(mCount);
            }
        });
    }
}

I hope you got the point and enjoy coding.

Google introduce ExifInterface Support Library

This is a class for reading and writing Exif tags in a JPEG file or a RAW image file. Supported formats are: JPEG, DNG, CR2, NEF, NRW, ARW, RW2, ORF and RAF.
Attribute mutation is supported for JPEG image files.


One thing that is important to understand with Exif data is that there are no required tags: each and every tag is optional - some services even specifically strip Exif data. Therefore throughout your code, you should always handle cases where there is no Exif data, either due to no data for a specific attribute or an image format that doesn't support Exif data at all (say, the ubiquitous PNGs or WebP images).

Add the ExifInterface Support Library to your project with the following dependency:

compile "com.android.support:exifinterface:25.1.0"
But when an Exif attribute is exactly what you need to prevent a mis-rotated image in your app, the ExifInterface Support Library is just what you need to #BuildBetterApps

The basics are still the same: the ability to read and write Exif tags embedded within image files: now with 140 different attributes (almost 100 of them new to Android 7.1/this Support Library!) including information about the camera itself, the camera settings, orientation, and GPS coordinates.

Camera Apps: Writing Exif Attributes

For Camera apps, the writing is probably the most important - writing attributes is still limited to JPEG image files. Now, normally you wouldn't need to use this during the actual camera capturing itself - you'd instead be calling the Camera2 API CaptureRequest.Builder.set() with JPEG_ORIENTATION, JPEG_GPS_LOCATION or the equivalents in the Camera1 Camera.Parameters. However, using ExifInterface allows you to make changes to the file after the fact (say, removing the location information on the user's request).

Reading Exif Attributes

For the rest of us though, reading those attributes is going to be our bread-and-butter; this is where we see the biggest improvements.

Firstly, you can read Exif data from JPEG and raw images (specifically, DNG, CR2, NEF, NRW, ARW, RW2, ORF, PEF, SRW and RAF files). Under the hood, this was a major restructuring, removing all native dependencies and building an extensive test suite to ensure that everything actually works.

For apps that receive images from other apps with a content:// URI (such as those sent by apps that target API 24 or higher), ExifInterface now works directly off of an InputStream; this allows you to easily extract Exif information directly out of content:// URIs you receive without having to create a temporary file.
Uri uri; // the URI you've received from the other app
InputStream in;
try {
  in = getContentResolver().openInputStream(uri);
  ExifInterface exifInterface = new ExifInterface(in);
  // Now you can extract any Exif tag you want
  // Assuming the image is a JPEG or supported raw format
} catch (IOException e) {
  // Handle any errors
} finally {
  if (in != null) {
    try {
      in.close();
    } catch (IOException ignored) {}
  }
}
Note: ExifInterface will not work with remote InputStreams, such as those returned from a HttpURLConnection. It is strongly recommended to only use them with content:// or file:// URIs.
For most attributes, you'd simply use the getAttributeInt(), getAttributeDouble(), or getAttribute() (for Strings) methods as appropriate.

One of the most important attributes when it comes to displaying images is the image orientation, stored in the aptly-named TAG_ORIENTATION, which returns one of the ORIENTATION_ constants. To convert this to a rotation angle, you can post-process the value.
int rotation = 0;
int orientation = exifInterface.getAttributeInt(
    ExifInterface.TAG_ORIENTATION,
    ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
  case ExifInterface.ORIENTATION_ROTATE_90:
    rotation = 90;
    break;
  case ExifInterface.ORIENTATION_ROTATE_180:
    rotation = 180;
    break;
  case ExifInterface.ORIENTATION_ROTATE_270:
    rotation = 270;
    break;
}
There are some helper methods to extract values from specific Exif tags. For location data, the getLatLong() method gives you the latitude and longitude as floats and getAltitude() will give you the altitude in meters. Some images also embed a small thumbnail. You can check for its existence with hasThumbnail() and then extract the byte[] representation of the thumbnail with getThumbnail() - perfect to pass to BitmapFactory.decodeByteArray().