Sunday, March 4, 2018

Android - Style drawer toggle


values/style.xml

<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <!-- The drawing color for the bars -->
    <item name="color">@android:color/white</item>
    <!-- Whether bars should rotate or not during transition -->
    <item name="spinBars">true</item>
    <!-- The total size of the drawable -->
    <item name="drawableSize">12sp</item>
    <!-- The max gap between the bars when they are parallel to each other -->
    <item name="gapBetweenBars">4sp</item>
    <!-- The thickness (stroke size) for the bar paint -->
    <item name="thickness">2sp</item>
</style>

<style name="CustomTheme" parent="Theme.AppCompat.NoActionBar">
    <!-- Add following -->
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>

AndroidManifest.xml

<application
    android:theme="@style/CustomTheme">
</application>

Android - Get battery capacity via reflection



double batteryCapacity = 0.f;

final String POWER_PROFILE_CLASS = "com.android.internal.os.PowerProfile";

try {
    mPowerProfile_ = Class.forName(POWER_PROFILE_CLASS)
            .getConstructor(Context.class).newInstance(this);
} catch (Exception e) {
    e.printStackTrace();
}

try {
    batteryCapacity = (Double) Class
            .forName(POWER_PROFILE_CLASS)
            .getMethod("getAveragePower", java.lang.String.class)
            .invoke(mPowerProfile_, "battery.capacity");
} catch (Exception e) {
    e.printStackTrace();
}

Thursday, November 23, 2017

Android - Turn flashlight on and off



private boolean isFlashSupported(PackageManager packageManager) {
    return packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}

private boolean isCameraSupported(PackageManager packageManager) {
    return packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA);
}

public void setTorchState(boolean torchState) {

        Log.v(LOG_TAG, "setTorchState - " + torchState);

        PackageManager packageManager = getPackageManager();

        if (isCameraSupported(packageManager) && isFlashSupported(packageManager)) {

            if (camera == null)
                try {
                    camera = Camera.open();
                } catch (Exception e) {
                    e.printStackTrace();
                    flashOn = false;
                }

            if (torchState) {
                if (camera != null) {
                    try {
                        Parameters param = camera.getParameters();
                        param.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                        camera.setParameters(param);
                        sleep(300);
                        camera.startPreview();
                        flashOn = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                        flashOn = false;
                    }
                }
            } else {
                if (camera != null) {
                    try {
                        Parameters param = camera.getParameters();
                        param.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                        camera.setParameters(param);
                        camera.stopPreview();
                        camera.release();
                        camera = null;
                        flashOn = false;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            sendBroadcast(new Intent(FLASHLIGHT_CHANGED)); // receive in custom receiver
        }
    }

Android - System settings observers

Observe auto-rotation changes



    /**
     * Observer to watch for changes to the Auto Rotation setting
     */
    private static class RotationObserver extends ContentObserver {

        private Context mContext;

        RotationObserver(Handler handler, Context context) {
            super(handler);
            mContext = context;
        }

        void startObserving() {
            ContentResolver resolver = mContext.getContentResolver();
            // Listen to accelerometer
            resolver.registerContentObserver(Settings.System.getUriFor
                            (Settings.System.ACCELEROMETER_ROTATION),
                    true, this);
        }

        void stopObserving() {
            mContext.getContentResolver().unregisterContentObserver(this);
        }

        @Override
        public void onChange(boolean selfChange) {
            Intent intent = new Intent(AUTO_ROTATE_CHANGED);
            mContext.sendBroadcast(intent); // receive in custom receiver
        }
    }

Observe brightness changes



    /**
     * Observer to watch for changes to the BRIGHTNESS setting
     */
    private static class BrightnessObserver extends ContentObserver {

        private Context mContext;

        BrightnessObserver(Handler handler, Context context) {
            super(handler);
            mContext = context;
        }

        void startObserving() {
            ContentResolver resolver = mContext.getContentResolver();
            // Listen to brightness and brightness mode
            resolver.registerContentObserver(Settings.System
                    .getUriFor(Settings.System.SCREEN_BRIGHTNESS), false, this);
            resolver.registerContentObserver(Settings.System
                    .getUriFor(Settings.System.SCREEN_BRIGHTNESS_MODE), false, this);
        }

        void stopObserving() {
            mContext.getContentResolver().unregisterContentObserver(this);
        }

        @Override
        public void onChange(boolean selfChange) {
            Intent intent = new Intent(BRIGHTNESS_CHANGED);
            mContext.sendBroadcast(intent); // receive in custom receiver
        }
    }

Use in Service


public class CustomService extends Service {
    ...
    private BrightnessObserver mBrightnessObserver ;
    private RotationObserver mRotationObserver;
    ...

    @Override
    public void onCreate() {
        super.onCreate();

        ...

        if (mSettingsObserver == null) {
            mSettingsObserver = new BrightnessObserver(new Handler(), this);
            mSettingsObserver.startObserving();
        }

        if (mRotationObserver == null) {
            mRotationObserver = new RotationObserver(new Handler(), this);
            mRotationObserver.startObserving();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        ...

        try {
            if (mSettingsObserver != null) {
                mSettingsObserver.stopObserving();
                mSettingsObserver = null;
            }

            if (mRotationObserver != null) {
                mRotationObserver.stopObserving();
                mRotationObserver = null;
            }

        } catch (Exception e) {
            Log.e(LOG_TAG, "", e);
        }
    }
}

Sunday, November 29, 2015

C/C++ - Getting fraction and exponent from double number using unions

Double is stored as 64-bit number, with following internal structure in computer registers:


This storage can be binary presented in C++ using unions, since their members share the same address space. That way we can have presentation of both exponent and fraction in one object:


typedef union 
{
 double db;
 unsigned short sh[4];
} Double;

Double D;
D.db = d; // some double
In this presentation, members of union have following meaning:

D.sh[0] - fraction (bits 15-0)
D.sh[1] - fraction (bits 31-16)
D.sh[2] - fraction (bits 47-32)
D.sh[3] - bit 15 is for sign 0 +, 1 -), bits 14-4 are for exponent, and bits 3-0 are part of fraction (bits 51-48)

From D.sh it is possible to extract sign, fraction (mantissa) and exponent:


short exp = ((D.sh[3] & 0x7FF0) >> 4) - 1023;
short sign = (D.sh[3] & 0x8000) >> 15;

double mant = 1.;

for (short i=0; i<16; i++)
{
 short bit = (D.sh[0] >> i) & 1; 
 mant += bit * pow (2., i-52);
}

for (short i=16; i<32; i++)
{
 short bit = (D.sh[1] >> (i-16)) & 1; 
 mant += bit * pow (2., i-52);
}

for (short i=32; i<48; i++)
{
 short bit = (D.sh[2] >> (i-32)) & 1; 
 mant += bit * pow (2., i-52);
}

for (short i=48; i<52; i++)
{
 short bit = (D.sh[3] >> (i-48)) & 1; 
 mant += bit * pow (2., i-52);
}

double dNew = pow(-1., sign) * mant * pow (2., exp); // should be the same as initial double d

Check binary file certificate

Certificates of binary files (executables or dynamic libraries) on Windows can be checked using available tool (signtool.exe) or by developing code using API procedures.

1. The utility signtool.exe is used to sign binaries, but it also allows overview of certificate information. Usage is described at location https://msdn.microsoft.com/en-us/library/windows/desktop/aa388171%28v=vs.85%29.aspx

2. WinVerifyTrust API gives information if file is signed and certificate is valid or not. Usage is described here: https://msdn.microsoft.com/en-us/library/aa388208%28v=vs.85%29.aspx.

3. Crypto API gives more information, similar to results of signtool.exe. Possible usage is described at https://support.microsoft.com/en-us/kb/323809.