Sources

Android Shortcuts: Most frequently used utilities

Noräs Salman Noräs Salman |

Tags: #Android #network #shortcuts #sources

Why wasting your time searching for peaces of code over when making Android projects. Android shortcut series provides a source for all android developers to copy and paste needed code.
In this article, I gather a set of utilities I use in most of projects, and usually find my self using over and over again. As usual: I will try to extend this over time.

Abstract view holder

Takes care of inflating and binding xml layouts. Perfect for isolating UI objects.


import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;

/**
 * Created by noras on 2018-12-04.
 **/

public abstract class AbstractViewHolder {


    /**
     * Context is used to get the inflater service and can be handy to get other resources in the bind
     **/
    private Context context;


    /**
     * The parent view that is inflated using the xml view
     **/
    private View convertView;


    /**
     * Event listener to update the view when object changes are made
     **/
    private DataSetChangeListener dataSetChangeListener;


    /**
     * Interface for the event listener
     **/
    public interface DataSetChangeListener {
        public void notifyChange();
    }


    /**
     * @param context        The context.. The activity..
     * @param layoutResource The xml view resource id
     **/
    public AbstractViewHolder(Context context, int layoutResource) {

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        this.convertView = inflater.inflate(layoutResource, null);

        this.context = context;

        /* Bind is called when the view is inflated */
        bindView(this.convertView);
    }


    /**
     * Binding the inflated view to the convert view (called in the constructor)
     *
     * @param convertView The inflated holder view.
     **/
    public abstract void bindView(View convertView);


    /**
     * Building the view using an object
     *
     * @param object The object that has the information which will be shown.
     **/
    public void buildView(Object object) {
        /*  Empty implementation where dynamic views can override the method for to bind an object the the view  */
    }


    /**
     * Listener for notifying host view.. requires implementation of the listener when called
     *
     * @param dataSetChangeListener the listener that will publish the event
     **/
    public void setDataSetChangeListener(DataSetChangeListener dataSetChangeListener) {
        this.dataSetChangeListener = dataSetChangeListener;
    }


    /**
     * Used in case an array adapter
     **/
    public void notifyDataSetChanged() {
        if (dataSetChangeListener != null)
            dataSetChangeListener.notifyChange();
    }


    /**
     * Returns the parent holderView
     **/
    public View getConvertView() {
        return convertView;
    }


    /**
     * Returns the context
     **/
    public Context getContext() {
        return context;
    }

}

Network Utility

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkUtility {
    public static final int TYPE_NOT_CONNECTED = 0;
    public static final int TYPE_MOBILE_DATA = 1;
    public static final int TYPE_WIFI = 2;
    //maybe there is a dummy or bluetooth connection type
    public static final int TYPE_OTHER = 3;

    public static int getConnectivityStatus(Context context) {
        //the connection manger
        ConnectivityManager connectivityManager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        //check if there is a connection at all
        if (networkInfo == null)
            return TYPE_NOT_CONNECTED;
        //check if it is wifi
        if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI)
            return TYPE_WIFI;
        //check if it is mobile data
        if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
            return TYPE_MOBILE_DATA;
        //a bluetooth or dummy
        return TYPE_OTHER;
    }

    public static boolean isNetworkAvailable(Context context) {
        return !(getConnectivityStatus(context) == TYPE_NOT_CONNECTED);
    }

    public static boolean isWiFiAvailable(Context context) {
        return getConnectivityStatus(context) == TYPE_WIFI;
    }

    public static boolean isMobileDataAvailable(Context context) {
        return getConnectivityStatus(context) == TYPE_MOBILE_DATA;
    }

}

Pixel and DP Converting Utility

import android.content.Context;

public class PixelUtil {
    public static int dpFromPx(final Context context, final float px) {
        return (int)(px / context.getResources().getDisplayMetrics().density);
    }

    public static int pxFromDp(final Context context, final float dp) {
        return (int)(dp * context.getResources().getDisplayMetrics().density);
    }

 public static int getWindowWidth(Context context){
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            return size.x;
        }

        public static int getWindowHeight(Context context){
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            return size.y;
        }
}

Shared preferences


import android.content.Context;
import android.content.SharedPreferences;

public class AppConfiguration {
    public static String APP_PREFERENCES= BuildConfig.APPLICATION_ID;

    public static String getSavedString(Context context, String name, String defaultValue) {
        SharedPreferences sharedpreferences = context.getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
        return sharedpreferences.getString(name, defaultValue);
    }

    public static void putSavedString(Context context, String name, String value) {
        SharedPreferences sharedpreferences = context.getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString(name, value);
        editor.commit();
    }

    public static int getSavedInt(Context context, String name, int defaultValue) {
        SharedPreferences sharedpreferences = context.getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
        return sharedpreferences.getInt(name, defaultValue);
    }
 

    public static void putSavedInt(Context context, String name, int value) {
        SharedPreferences sharedpreferences = context.getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putInt(name, value);
        editor.commit();
    }

    public static boolean getSavedBoolean(Context context, String name, boolean defaultValue) {
        SharedPreferences sharedpreferences = context.getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
        return sharedpreferences.getBoolean(name, defaultValue);
    }

    public static void putSavedBoolean(Context context, String name, boolean value) {
        SharedPreferences sharedpreferences = context.getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putBoolean(name, value);
        editor.commit();
    }
    
}

Timestamp Utility


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimestampUtility {

    /* Make this value negative if you don't want to show NOW label (30 is good otherwise)*/
    private static final int NOW_DIFFERENCE_IN_SECONDS = -1;
    
    /* Labels (Use strings resources in case you support a multilingual application) */
    private static final String NOW = "now";
    private static final String SECOND = "second";
    private static final String SECONDS = "seconds";
    private static final String MINUTE = "minute";
    private static final String MINUTES = "minutes";
    private static final String HOUR = "hour";
    private static final String HOURS = "hours";
    private static final String DAY = "day";
    private static final String DAYS = "days";
    private static final String WEEK = "week";
    private static final String WEEKS = "weeks";
    private static final String MONTH = "month";
    private static final String MONTHS = "months";
    private static final String YEAR = "year";
    private static final String YEARS = "years";
    private static final String SEPARATOR = " ";

    /**
     * returns a long timestamp value (milliseconds)
     * @param mostRecent usually used as now (System.currentTimeMillis())
     * @param old        the timestamp in milliseconds that you want you get the label for.
     * **/
    public static String getHumanReadableDiff(long mostRecent, long old) {
        long diff = (mostRecent - old);
        int seconds = (int) (diff / 1000);
        int minutes = (int) (seconds / 60);
        int hours = (int) (minutes / 60);
        int days = (int) (hours / 24);
        int weeks = (int) (days / 7);
        int months = (int) (days / 30);
        int years = (int) (months / 12);

        if (seconds < NOW_DIFFERENCE_IN_SECONDS)
            return NOW;
        else if (seconds < 60)
            return (seconds == 1 ? seconds + SEPARATOR + SECOND : seconds + SEPARATOR + SECONDS);
        else if (minutes < 60)
            return (minutes == 1 ? minutes + SEPARATOR + MINUTE : minutes + SEPARATOR + MINUTES);
        else if (hours < 24)
            return (hours == 1 ? hours + SEPARATOR + HOUR : hours + SEPARATOR + HOURS);
        else if (days < 7)
            return (days == 1 ? days + SEPARATOR + DAY : days + SEPARATOR + DAYS);
        else if (days < 30)
            return (weeks == 1 ? weeks + SEPARATOR + WEEK : weeks + SEPARATOR + WEEKS);
        else  if (months < 12)
            return (months == 1 ? months + SEPARATOR + MONTH : months + SEPARATOR + MONTHS);
        else
            return (years == 1 ? years + SEPARATOR + YEAR : years + SEPARATOR + YEARS);
    }

    
    /** 
     * returns a long timestamp value in (milliseconds)
     * @param timestamp the timestamp as a string
     * @param pattern   the pattern that the passed string is written in ex: yyyy-MM-dd HH:mm:ss
     * **/
    public static long getTimeFromString(String timestamp,String pattern) throws ParseException {
        DateFormat formatter = new SimpleDateFormat(pattern);
        Date d = formatter.parse(timestamp);
        return d.getTime();
    }
}

Hashing utility

import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;


public class HashingUtils {
    public static String generateHashWithHmac256(String message, String key) {
        String messageDigest=null;
        try {
            final String hashingAlgorithm = "HmacSHA256"; //or "HmacSHA1", "HmacSHA512"

            byte[] bytes = hmac(hashingAlgorithm, key.getBytes(), message.getBytes());

            messageDigest = bytesToHex(bytes);

            Log.i(TAG, "message digest: " + messageDigest);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return messageDigest;
    }

    public static byte[] hmac(String algorithm, byte[] key, byte[] message) throws NoSuchAlgorithmException, InvalidKeyException {
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(message);
    }

    public static String bytesToHex(byte[] bytes) {
        final char[] hexArray = "0123456789abcdef".toCharArray();
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0, v; j < bytes.length; j++) {
            v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }


    public static  String MD5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(data.getBytes("UTF-8"));
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
        } catch(UnsupportedEncodingException ex){
        }
        return null;
    }
}

Share and Rate intents

    public void shareApplication(){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id="+getApplicationContext().getPackageName());
        intent.setType("text/plain");
        startActivity(Intent.createChooser(intent, "Share via"));
    }
    
    public void rateApplication(){
        Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
        Intent marketIntent = new Intent(Intent.ACTION_VIEW, uri);
        marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |  Intent.FLAG_ACTIVITY_NEW_DOCUMENT |  Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
        try {
            startActivity(marketIntent);
        } catch (ActivityNotFoundException e) {
            startActivity(new Intent(Intent.ACTION_VIEW,    Uri.parse("http://play.google.com/store/apps/details?id=" + getApplicationContext().getPackageName())));
        }
    }

About the author

Noräs Salman

"Senior Software Engineer. MSc in Computer systems and Networks with big interest in security. Loves to play with Android code and does security research for fun and profit. Speaks 4 languages and codes in much more."

Related articles

Tags: #Android #network #shortcuts #sources




Copyright © 2019 - nindoda.com