Color animation using ValueAnimator on Android

int colorFrom = getResources().getColor(R.color.red);
int colorTo = getResources().getColor(R.color.blue);
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.setDuration(250); // milliseconds
colorAnimation.addUpdateListener(new AnimatorUpdateListener() {

    @Override
    public void onAnimationUpdate(ValueAnimator animator) {
        textView.setBackgroundColor((int) animator.getAnimatedValue());
    }

});
colorAnimation.start();

References
https://stackoverflow.com/questions/2614545/animate-change-of-view-background-color-on-android

Prevent services of Android app from being killed using Intent.ACTION_TIME_TICK

// register intent time tick receiver which ticks every minute
registerReceiver(timeTickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
    /**
     * restart service every minute if it's killed
     */
    private BroadcastReceiver timeTickReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                boolean isServiceRunning = false;

                if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {

                    ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);

                    if (manager != null) {
                        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                            if ("net.pupli.monitoring.MyMqttService".equals(service.service.getClassName())) {
                                isServiceRunning = true;
                            }
                        }
                    }

                    if (!isServiceRunning) {
                        Intent i = new Intent(context, MyMqttService.class);
                        context.startService(i);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };

References
https://llin233.github.io/2015/11/16/How-to-prevent-service/
https://developer.android.com/reference/android/content/Intent#action_time_tick
https://medium.com/google-developers/who-lives-and-who-dies-process-priorities-on-android-cb151f39044f
http://sourabhsoni.com/how-to-use-intent-action_time_tick/

Detect Outlier values in Java Using BoxPlot formula and Apache Commons Math Library

public boolean isOutlier(List<RawItem> rawItems, String value) {

        DescriptiveStatistics descriptiveStatistics = new DescriptiveStatistics();
        double dValue = Double.parseDouble(value);

        for (RawItem rawItem : rawItems) {
            double d = Double.parseDouble(rawItem.getValue());

            descriptiveStatistics.addValue(d);
        }

        double Q1 = descriptiveStatistics.getPercentile(25);
        double Q3 = descriptiveStatistics.getPercentile(75);
        double IQR = Q3 - Q1;

        double highRange = Q3 + 3 * IQR;
        double lowRange = Q1 - 3 * IQR;

        if (dValue > highRange || dValue < lowRange) {
            return true;
        }

        return true;
    }

References
https://www.shmoop.com/basic-statistics-probability/box-whisker-plots.html
http://www.baeldung.com/apache-commons-math
https://stackoverflow.com/questions/22888902/get-median-from-number-series-using-apache-commons-math

Guide to Guava’s EventBus in Java

Setup

EventBus eventBus = new EventBus();

Creating Listeners

public class EventListener {
 
    private static int eventsHandled;
 
    @Subscribe
    public void stringEvent(String event) {
        eventsHandled++;
    }
}

Registering Listeners

EventListener listener = new EventListener();
eventBus.register(listener);

Unregistering Listeners

eventBus.unregister(listener);

Posting Events

@Test
public void givenStringEvent_whenEventHandled_thenSuccess() {
    eventBus.post("String Event");
    assertEquals(1, listener.getEventsHandled());
}

Posting Custom Events

public class CustomEvent {
    private String action;
 
    // standard getters/setters and constructors
}
@Subscribe
public void someCustomEvent(CustomEvent customEvent) {
    eventsHandled++;
}
@Test
public void givenCustomEvent_whenEventHandled_thenSuccess() {
    CustomEvent customEvent = new CustomEvent("Custom Event");
    eventBus.post(customEvent);
 
    assertEquals(1, listener.getEventsHandled());
}

Handling an Unsubscribed Event

@Subscribe
public void handleDeadEvent(DeadEvent deadEvent) {
    eventsHandled++;
}

References
http://www.baeldung.com/guava-eventbus

Android Notifications

 public void createNotification(View view) {
        // Prepare intent which is triggered if the
        // notification is selected
        Intent intent = new Intent(this, NotificationReceiverActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);

        // Build notification
        // Actions are just fake
        Notification noti = new Notification.Builder(this)
                .setContentTitle("New mail from " + "[email protected]")
                .setContentText("Subject")
                .setSmallIcon(R.drawable.icon)
                .setContentIntent(pIntent)
                .setTicker("Subject")
                .addAction(R.drawable.icon, "Call", pIntent)
                .addAction(R.drawable.icon, "More", pIntent)
                .addAction(R.drawable.icon, "And more", pIntent).build();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // hide the notification after its selected
        noti.flags |= Notification.FLAG_AUTO_CANCEL;

        notificationManager.notify(0, noti);

    }

or start foreground service

startForeground(101,notification);

References
http://www.vogella.com/tutorials/AndroidNotifications/article.html
https://questdot.com/android-foreground-service/

Keep the screen awake on Android

public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  }

or

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">
    ...
</RelativeLayout>

References
https://developer.android.com/training/scheduling/wakelock

Updating the UI from a Timer using Handler on Android

private Handler handler = new Handler();
handler.postDelayed(runnable, 100);
private Runnable runnable = new Runnable() {
   @Override
   public void run() {
      /* do what you need to do */
      foobar();
      /* and here comes the "trick" */
      handler.postDelayed(this, 100);
   }
};

If you want it to stop, you can just call handler.removeCallback(runnable) and it won’t start again, until you tell it to

References
http://www.mopri.de/2010/timertask-bad-do-it-the-android-way-use-a-handler/