Skip to content

Instantly share code, notes, and snippets.

@findjigar
findjigar / AndroidExt.kt
Created February 26, 2020 03:30
Useful extension functions for Andorid
/**
* Extension function on [Context] to get current battery level
*/
fun Context.getBatteryLevel(): Float? {
val batteryStatus: Intent? = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
batteryStatus?.let { intent ->
val level: Int = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale: Int = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
return level * 100 / scale.toFloat()
}
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
/** Helper to avoid implementing all lifecycle callback methods. */
public class ActivityLifecycleCallbacksAdapter implements Application.ActivityLifecycleCallbacks {
@Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
import android.content.Context;
import android.os.Debug;
import java.io.File;
public class OomExceptionHandler implements Thread.UncaughtExceptionHandler {
private static final String FILENAME = "out-of-memory.hprof";
public static void install(Context context) {
Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
/*
* Copyright (C) 2014 Chris Banes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software