hyuni
9/15/2015 - 6:12 AM

Android Snippets

Android Snippets

    private void setViewGroupSize(View view, int width, int height) {
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        if (layoutParams != null) {
            layoutParams.width = width;
            layoutParams.height = height;
        }
        view.setLayoutParams(layoutParams);
    }
private void setOrientationBasedOnPreference() {
  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
  if (prefs.getBoolean(PreferencesActivity.KEY_DISABLE_AUTO_ORIENTATION, true)) {
    setRequestedOrientation(getCurrentOrientation());
  } else {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
  }
}
//region MediaPlayer.OnVideoSizeChangedListener
@Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height)
{
  setFitToFillAspectRatio(mSurfaceViewContainer, mSurfaceView, width, height);
}
//endregion

private void setFitToFillAspectRatio(View container, View inner, int videoWidth, int videoHeight) {
  Point containerSize = new Point(container.getWidth(), container.getHeight());
  Point innerSize = new Point(0, 0);
  if (videoWidth > videoHeight) {
    innerSize.x = containerSize.x;
    innerSize.y = containerSize.x * videoHeight / videoWidth;
  } else {
    innerSize.x = containerSize.y * videoWidth / videoHeight;
    innerSize.y = containerSize.y;
  }
  setViewGroupSize(inner, innerSize);
}

private void setViewGroupSize(View view, Point size) {
  ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
  if (layoutParams != null) {
    layoutParams.width = size.x;
    layoutParams.height = size.y;
  }
  view.setLayoutParams(layoutParams);
}
public static void sendViewToBack(final View child) {
  final ViewGroup parent = (ViewGroup)child.getParent();
  if (null != parent) {
    parent.removeView(child);
    parent.addView(child, 0);
  }
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
  switch (keyCode)
  {
    case KeyEvent.KEYCODE_BACK:
      // do nothing
      break;
    case KeyEvent.KEYCODE_FOCUS:
    case KeyEvent.KEYCODE_CAMERA:
      // Handle these events so they don't launch the Camera app
      return true;
    // Use volume up/down to turn on light
    case KeyEvent.KEYCODE_VOLUME_DOWN:
      onVolumeDown();
      return true;
    case KeyEvent.KEYCODE_VOLUME_UP:
      onVolumeUp();
      return true;
  }
  return super.onKeyDown(keyCode, event);
}
// REF: http://android-developers.blogspot.com.au/2011/03/identifying-app-installations.html
public class Installation {
    private static String sID = null;
    private static final String INSTALLATION = "INSTALLATION";

    public synchronized static String id(Context context) {
        if (sID == null) {  
            File installation = new File(context.getFilesDir(), INSTALLATION);
            try {
                if (!installation.exists())
                    writeInstallationFile(installation);
                sID = readInstallationFile(installation);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return sID;
    }

    private static String readInstallationFile(File installation) throws IOException {
        RandomAccessFile f = new RandomAccessFile(installation, "r");
        byte[] bytes = new byte[(int) f.length()];
        f.readFully(bytes);
        f.close();
        return new String(bytes);
    }

    private static void writeInstallationFile(File installation) throws IOException {
        FileOutputStream out = new FileOutputStream(installation);
        String id = UUID.randomUUID().toString();
        out.write(id.getBytes());
        out.close();
    }
}
import android.content.Context;
import android.content.SharedPreferences;

import java.util.UUID;

public class AppUtils {

    private static String uniqueID = null;
    private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";

    public synchronized static String id(Context context) {
        if (uniqueID == null) {
            SharedPreferences sharedPrefs = context.getSharedPreferences(
                    PREF_UNIQUE_ID, Context.MODE_PRIVATE);
            uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
            if (uniqueID == null) {
                uniqueID = UUID.randomUUID().toString();
                SharedPreferences.Editor editor = sharedPrefs.edit();
                editor.putString(PREF_UNIQUE_ID, uniqueID);
                editor.commit();
            }
        }
        return uniqueID;
    }
}
    private Point getScreenSize() {
        Point p = new Point(-1, -1);

        WindowManager w = getWindowManager();
        Display d = w.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        d.getMetrics(metrics);

        // since SDK_INT = 1;
        p.x = metrics.widthPixels;
        p.y = metrics.heightPixels;

        // includes window decorations (status bar/menu bar)
        if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) {
            try {
                p.x = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
                p.y = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
            } catch (Exception ignored) {
            }
        }

        // includes window decorations (status bar/menu bar)
        if (Build.VERSION.SDK_INT >= 17) {
            try {
                Point realSize = new Point();
                Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
                p.x = realSize.x;
                p.y = realSize.y;
            } catch (Exception ignored) {
            }
        }

        return p;
    }
public class ScreenOrientationUtils {

    public static int getRotation(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        return windowManager.getDefaultDisplay().getRotation();
    }

    public static String getRotationString(int rotation) {
        String rotationString = "";
        switch (rotation) {
            case Surface.ROTATION_0:
                rotationString = "Surface.ROTATION_0";
                break;
            case Surface.ROTATION_90:
                rotationString = "Surface.ROTATION_90";
                break;
            case Surface.ROTATION_180:
                rotationString = "Surface.ROTATION_180";
                break;
            case Surface.ROTATION_270:
                rotationString = "Surface.ROTATION_270";
                break;
            default:
                rotationString = "Unknown";
                break;
        }
        return rotationString;
    }

    public static int getOrientation(Context context) {
        return context.getResources().getConfiguration().orientation;
    }

    public static ScreenOrientation getScreenOrientation(Context context) {
        ScreenOrientation screenOrientation = null;

        int o = getOrientation(context);
        int r = getRotation(context);

        switch (o) {
            case Configuration.ORIENTATION_LANDSCAPE:
                switch (r) {
                    case Surface.ROTATION_0:
                    case Surface.ROTATION_90:
                        screenOrientation = ScreenOrientation.SCREEN_ORIENTATION_LANDSCAPE;
                        break;
                    case Surface.ROTATION_180:
                    case Surface.ROTATION_270:
                        screenOrientation = ScreenOrientation.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
                        break;
                    default:
                        screenOrientation = ScreenOrientation.SCREEN_ORIENTATION_UNSPECIFIED;
                        break;
                }
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                switch (r) {
                    case Surface.ROTATION_0:
                    case Surface.ROTATION_90:
                        screenOrientation = ScreenOrientation.SCREEN_ORIENTATION_PORTRAIT;
                        break;
                    case Surface.ROTATION_180:
                    case Surface.ROTATION_270:
                        screenOrientation = ScreenOrientation.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
                        break;
                    default:
                        screenOrientation = ScreenOrientation.SCREEN_ORIENTATION_UNSPECIFIED;
                        break;
                }
                break;
            default:
                screenOrientation = ScreenOrientation.SCREEN_ORIENTATION_UNSPECIFIED;
                break;
        }

        return screenOrientation;
    }

  public enum ScreenOrientation {
  
      SCREEN_ORIENTATION_UNSPECIFIED(-1),
      SCREEN_ORIENTATION_PORTRAIT(0),
      SCREEN_ORIENTATION_REVERSE_PORTRAIT(1),
      SCREEN_ORIENTATION_LANDSCAPE(2),
      SCREEN_ORIENTATION_REVERSE_LANDSCAPE(3),
      ;
  
      private int mId;
  
      private ScreenOrientation(int id) {
          this.mId = id;
      }
  
      public int getId() {
          return mId;
      }
  
      public void setId(int id) {
          this.mId = id;
      }
  
      public boolean compareTo(int id) {
          return this.mId == id;
      }
  
      public static ScreenOrientation getValue(int id) {
          ScreenOrientation[] orientations = ScreenOrientation.values();
          for(int i = 0; i < orientations.length; i++) {
              if (orientations[i].compareTo(id)) {
                  return orientations[i];
              }
          }
          return SCREEN_ORIENTATION_UNSPECIFIED;
      }
  
      public static ScreenOrientation fromId(int id) {
          switch (id) {
              case 0:
                  return SCREEN_ORIENTATION_PORTRAIT;
              case 1:
                  return SCREEN_ORIENTATION_REVERSE_PORTRAIT;
              case 2:
                  return SCREEN_ORIENTATION_LANDSCAPE;
              case 3:
                  return SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
              default:
                  return SCREEN_ORIENTATION_UNSPECIFIED;
          }
      }
  
  }
}

LIVE TEMPLATES

NOTE: Ensure "Skip if defined" is checked for all variables (unless otherwise specified).

  1. TEMPLATE
  • ABBREVIATION: abr
  • DESCRIPTION: Long Description (appears in popup)
  • TEMPLATE TEXT: null; // code to produce
  • VARIABLES:
    • NAME: Expression
  1. TAG
  • ABBREVIATION: tag
  • DESCRIPTION: Class Tag
  • TEMPLATE TEXT: private static final String TAG = $CLASS_NAME$.class.getSimpleName();
  • VARIABLES:
    • CLASS_NAME: className()
  1. LOG UTIL NEW
  • ABBREVIATION: lun
  • DESCRIPTION: Log Util New
  • TEMPLATE TEXT: LogUtils mLogUtils = new LogUtils(TAG);
  1. LOG UTIL START
  • ABBREVIATION: lus
  • DESCRIPTION: Log Util Start
  • TEMPLATE TEXT: mLogUtils.setMethod("$METHOD_NAME$").addMessage("start")$PARMS$.logToD();
  • VARIABLES:
    • METHOD_NAME: methodName()
    • PARAMS: groovyScript("_1.collect { '.add(\"' + it + '\", ' + it +')' }.join()", methodParameters())
  1. LOG UTIL MSG
  • ABBREVIATION: lum
  • DESCRIPTION: Log Util Msg
  • TEMPLATE TEXT: mLogUtils.setMethod("$METHOD_NAME$").addMessage("$END$").logToD();
  • VARIABLES:
    • METHOD_NAME: methodName()
  1. LOG UTIL END
  • ABBREVIATION: lue
  • DESCRIPTION: Log Util End
  • TEMPLATE TEXT: mLogUtils.setMethod("$METHOD_NAME$").addMessage("end").logToD();
  • VARIABLES:
    • METHOD_NAME: methodName()
  1. LOG UTIL SURROUND
  • ABBREVIATION: lub
  • DESCRIPTION: Log Util Box
  • TEMPLATE TEXT: mLogUtils.setMethod("$METHOD_NAME$").add("$SELECTION$", $SELECTION$).logToD();
  • VARIABLES:
    • METHOD_NAME: methodName()
package com.fuhoi.android.utils;

import android.util.Log;
import android.util.Pair;

import java.util.ArrayList;

/**
 * LogUtils
 * Helper class for logging using JSON format (other formats to be added as needed)
 * Supports method chaining
 *
 * Typical use:
 *      private LogUtils mLogUtils = new LogUtils(TAG);
 *
 *      @Override
 *      protected void onCreate(Bundle savedInstanceState) {
 *          mLogUtils.setMethod("onCreate").addMessage("start").add("savedInstanceState", savedInstanceState).logToD();
 *          mLogUtils.setMethod("onCreate").addMessage("end").logToD();
 *      }
 *
 * One line log:
 *      new LogUtils(TAG)
 *          .setMethod("onCreate")
 *          .addMessage("start")
 *          .add("savedInstanceState", savedInstanceState)
 *          .logToD();
 *
 * To string for any class
 *      @Override
 *      public String toString() {
 *          return new LogUtils(TAG)
 *              .add("savedInstanceState", savedInstanceState)
 *              .toString();
 *      }
 *
 * @author adaml
 * @date 11/02/2014
 */

public class LogUtils {

    private static final String TAG = LogUtils.class.getSimpleName();

    private static final boolean APPEND_CLAZZ = false;
    private static final boolean APPEND_METHOD = true;

    private static final boolean DEFAULT_ENABLED = true;
    private static final String DEFAULT_DELIMITER = ", ";
    private static final String DEFAULT_PREFIX = "{";
    private static final String DEFAULT_SUFFIX = "}";
    private static final String DEFAULT_FORMAT = "'%s': '%s'";
    private static final String DEFAULT_NULL_TEXT = "null";
    private static final String ELLIPSIZE_TEXT = "...";
    private static final int ELLIPSIZE_TEXT_LENGTH = 3;
    private static final int MAX_LOG_LENGTH = 100;
    private static final int TRUNCATED_LOG_LENGTH = 97; // max length of log minus ELLIPSIZE_TEXT.length()

    private String mClazz;
    private String mMethod;
    private boolean mEnabled;
    private ArrayList<Pair<String, Object>> mPairs = new ArrayList<Pair<String, Object>>();

    public LogUtils() {
        this(null, null, DEFAULT_ENABLED);
    }

    public LogUtils(String clazz) {
        this(clazz, null, DEFAULT_ENABLED);
    }

    public LogUtils(String clazz, boolean enabled) {
        this(clazz, null, enabled);
    }

    public LogUtils(String clazz, String method) {
        this(clazz, method, DEFAULT_ENABLED);
    }

    public LogUtils(String clazz, String method, boolean enabled) {
        setClazz(clazz);
        setMethod(method);
        setEnabled(enabled);
    }

    public LogUtils setClazz(String clazz) {
        mClazz = clazz;
        return this;
    }

    public String getClazz() {
        return mClazz != null ? mClazz : TAG;  // return this class as a default
    }

    public LogUtils setMethod(String method) {
        mMethod = method;
        return this;
    }

    public String getMethod() {
        return mMethod;  // no default case
    }

    public LogUtils setEnabled(boolean enabled) {
        mEnabled = enabled;
        return this;
    }
    
    public boolean getEnabled() {
        return mEnabled;
    }

    public LogUtils addMessage(String message) {
        mPairs.add(new Pair<String, Object>("MESSAGE", message));
        return this;
    }

    public LogUtils add(String key, Object value) {
        mPairs.add(new Pair<String, Object>(key, value));
        return this;
    }

    public LogUtils clear() {
        //mClazz = null;
        mMethod = null;
        //mPairs = new ArrayList<Pair<String, Object>>();
        mPairs.clear();
        return this;
    }

    /**
     * Logs to debug output and clears method and params
     * @return
     */
    public void logToD() {
        if (mEnabled) {
            Log.d(getClazz(), this.toString());  // toString() will clear
        } else {
            clear();
        }
    }

    private String ellipsize(String value) {
        return value.length() > ELLIPSIZE_TEXT_LENGTH + 1 && value.length() > MAX_LOG_LENGTH ?
                value.substring(0, TRUNCATED_LOG_LENGTH).trim() + ELLIPSIZE_TEXT :
                value;
    }

    private String formatString(String key, String value) {
        return String.format(DEFAULT_FORMAT, key, value);
    }

    private String formatString(String key, Object object) {
        if (object != null) {
            /*
             * NOTE: Don't ellipsize container classes (arrays, collections), just their contents
             * Each class should limit the number of items in toString() if required
             * If each class uses this LogUtils class then the format will be correct
             */
            if (object instanceof String) {
                String val = object.toString();
                if (val.startsWith("http")) {  // print HTTP in full to assist debugging
                    return formatString(key, val);
                } else {
                    return formatString(key, ellipsize(val));
                }
            } else {
                return formatString(key, object.toString());
            }
        }
        return formatString(key, DEFAULT_NULL_TEXT);
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(DEFAULT_PREFIX);

        if (APPEND_CLAZZ) {
            stringBuilder.append(formatString("CLASS", getClazz())).append(DEFAULT_DELIMITER);
        }

        if (APPEND_METHOD) {
            if (mMethod != null) {
                stringBuilder.append(formatString("METHOD", getMethod())).append(DEFAULT_DELIMITER);
            }
        }

        if (mPairs != null && mPairs.size() > 0) {
            for (Pair<String, Object> pair : mPairs) {
                stringBuilder.append(formatString(pair.first, pair.second)).append(DEFAULT_DELIMITER);
            }
        }

        stringBuilder.setLength(stringBuilder.length() - DEFAULT_DELIMITER.length());  // remove last occurrence of delimiter
        stringBuilder.append(DEFAULT_SUFFIX);

        clear();  // clear every time toString is called

        return stringBuilder.toString();
    }
}
# IGNORE NATIVE GET ENABLED TAGS

* `^(?!.*(nativeGetEnabledTags)).*$`

# IGNORE DALVIKVM HEAP MESSAGES

* `^(?!.*(nativeGetEnabledTags|GC_FOR_ALLOC|GC_EXPLICIT|GC_CONCURRENT|Grow heap)).*$`
package $PACKAGE_NAME$;

import android.app.Activity;
import android.os.Handler;
import android.widget.Toast;

public class DoubleBackToExit extends Activity
{
    private static final int DOUBLE_PRESS_BACK_TO_EXIT_RESET_DELAY_MSEC = 2000;  // length of Toast.LENGTH_SHORT
    private static final String DOUBLE_PRESS_BACK_TO_EXIT_TOAST_TEXT = "Press again to exit";
    private boolean mDoublePressBackToExit = false;
    private boolean mIsBackPressedByTheUser = false;

    @Override
    public void onBackPressed()
    {
        if (mDoublePressBackToExit)
        {
            // process the back button as per normal
            mIsBackPressedByTheUser = true;
            super.onBackPressed();
            return;
        }
        
        mDoublePressBackToExit = true;  // set flag
        Toast.makeText(this, DOUBLE_PRESS_BACK_TO_EXIT_TOAST_TEXT, Toast.LENGTH_SHORT).show();

        // reset after time delay
        new Handler().postDelayed(
            new Runnable() {
                @Override
                public void run() {
                    mDoublePressBackToExit = false;
                }
            }, DOUBLE_PRESS_BACK_TO_EXIT_RESET_DELAY_MSEC
        );
    }
}

ANDROID SNIPPETS

  • This is a collection of android snippets