Skip to content

Instantly share code, notes, and snippets.

@TeWu
Last active August 29, 2015 14:23
Show Gist options
  • Save TeWu/c2d14f66cc26c301d649 to your computer and use it in GitHub Desktop.
Save TeWu/c2d14f66cc26c301d649 to your computer and use it in GitHub Desktop.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.example.battery_level_monitor_example"
android:versionCode="1"
android:versionName="0.0.1">
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:label="@string/app_name">
<receiver android:name=".PowerConnectionReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
</application>
</manifest>
/*
* INFO:
* http://developer.android.com/training/monitoring-device-state/battery-monitoring.html
*/
import android.content.{BroadcastReceiver, Context, Intent}
import android.os.BatteryManager
import org.apache.http.HttpResponse
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.{StringEntity, ByteArrayEntity}
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.params.{HttpConnectionParams, BasicHttpParams}
class PowerConnectionReceiver extends BroadcastReceiver {
val TARGET_URL = "http://example.org/targetScript"
override def onReceive(context: Context, intent: Intent) {
val json = createJSON(intent)
execPostRequest(TARGET_URL, json)
}
def createJSON(intent: Intent): String = {
// Extract info from intent
val status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
val chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
val batteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val batteryScale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
val batteryPercent = batteryLevel / batteryScale.toFloat
val isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL
val isChargingViaUSB = chargePlug == BatteryManager.BATTERY_PLUGGED_USB
val isChargingViaACCharger = chargePlug == BatteryManager.BATTERY_PLUGGED_AC
// Create and return JSON object as string
???
}
def execPostRequest(uri: String, message: String, timeout: Int = 30000): HttpResponse = {
val httpParams = new BasicHttpParams
HttpConnectionParams.setSoTimeout(httpParams, timeout)
val client = new DefaultHttpClient(httpParams)
val request = new HttpPost(uri)
request.setEntity(new StringEntity(message))
client.execute(request)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment