Saturday, December 21, 2013

Android Get Current Battery Level

Get current battery level once on Android platform by using Battery_Changed Intent. This gets total scale value and current level to calculate.

public float getCurrentBatteryLevel() {
        Intent battery = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        
        int batteryLevel = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        
        int batteryScale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

        //to avoid error use this
        if(batteryLevel == -1 || batteryScale == -1) {            
                return 50.0f;
        }

        return ((float)batteryLevel / (float)batteryScale) * 100.0f;
    }

Android - Turn WiFi Hotspot On and Off Programmatically


Programmatically turn WiFi Hotspot On and Off on android platform using following permissions in Manifest file.

android.permission.ACCESS_WIFI_STATE
android.permission.CHANGE_WIFI_STATE

and following code

WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

WifiConfiguration wifi_config = null;

wifi.setWifiEnabled(false); //True or False

//There is no direct call so use following... //USE REFLECTION ON THE METHOD NAMED //SetWifiAPEnabled//
Method methodAP = wifi.getClass().getMethod("setWifiApEnabled", WifiConfig.class, boolean.class);

methodAP.invoke(wifi, wifi_config, false); //True or False


    

Android - Turn WiFi On and Off Programmatically


Programmatically turn WiFi On and Off on android platform using following permissions in Manifest file.

android.permission.ACCESS_WIFI_STATE
android.permission.CHANGE_WIFI_STATE

and following code

WifiManager wifi_manager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
wifi_manager.setWifiEnabled(false); //True or False