Android Framework How to use and extend it
Lectures 9/10 Android Security Security threats Security gates Android Security model Bound Services Complex interactions with Services Alberto Panizzo 2
Lecture 11 Sensors Interface Application's widgets Tip: How to catch memory leaks Alberto Panizzo 3
Sensors Alberto Panizzo 4
Sensors Based on architecture Service/Manager [1] Alberto Panizzo 5
Sensors Connect with SensorsService private SensorManager msensormanager;... msensormanager = (SensorManager) getsystemservice(context.sensor_service); Get the list of supported sensors List<Sensor> devicesensors = msensormanager.getsensorlist(sensor.type_all); Get the default sensor per type Sensor s = msensormanager.getdefaultsensor(sensor.type_magnetic_field) if (s!= null) { // Success! There's a magnetometer. } else { // Failure! No magnetometer. } Alberto Panizzo 6
Sensor properties The Sensor object gives properties of the controlled hw: getvendor() and getversion() to handle vendor diffs getmaximumrange() and getresolution(): to understand the sample. getpower() to know how much this sensor consume Alberto Panizzo 7
Sensor events To handle sensor's samples, must be registered a SensorEventListener on the obtained sensor. The callbacks are: void onaccuracychanged(sensor sensor, int accuracy) The system publicize the reliability of the sensor. void onsensorchanged(sensorevent event) Handle the new sensor sample event with: Accuracy, the sensor that generated the data, timestamp and the new data. Alberto Panizzo 8
Sensor events public class SensorActivity extends Activity implements SensorEventListener { private SensorManager msensormanager; private Sensor mlight; @Override public final void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); msensormanager = (SensorManager) getsystemservice(context.sensor_service); mlight = msensormanager.getdefaultsensor(sensor.type_light); } @Override protected void onresume() { super.onresume(); msensormanager.registerlistener(this, mlight, SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onpause() { super.onpause(); msensormanager.unregisterlistener(this); }... Alberto Panizzo 9
Sensor events... @Override public final void onaccuracychanged(sensor sensor, int accuracy) { // Do something here if sensor accuracy changes. } } @Override public final void onsensorchanged(sensorevent event) { // The light sensor returns a single value. // Many sensors return 3 values, one for each axis. float lux = event.values[0]; // Do something with this sensor value. } Alberto Panizzo 10
Lecture 11 Sensors Interface Application's widgets Tip: How to catch memory leaks Alberto Panizzo 11
AppWidget Allows applications to manage graphics contents inside another application (Usually the Launcher) AppWidgets are managed by the AppWidgetService, through its manager: AppWidgetManager The Hosting application holds an instance of AppWidgetHost which manage the AppWidget's ids lifecycles and generates the View's stubs The Provider application expose its AppWidget's provider which will implement the needed behavior [2] Alberto Panizzo 12
AppWidget architecture Alberto Panizzo 13
AppWidget architecture Alberto Panizzo 14
AppWidget architecture Alberto Panizzo 15
AppWidget architecture Alberto Panizzo 16
AppWidgetProvider The AppWidgetProvider class is a direct descendant of BroadcastReceiver where the onreceive() method listen to the AppWidget's lifecycle actions redirecting these to local callbacks: // Called on android.appwidget.action.appwidget_enabled public void onenabled(context context) // Called on android.appwidget.action.appwidget_update public void onupdate(context context, AppWidgetManager appwidgetmanager, int[] appwidgetids) // Called on android.appwidget.action.appwidget_deleted public void ondeleted(context context, int[] appwidgetids) // Called on android.appwidget.action.appwidget_disabled public void ondisabled(context context) Alberto Panizzo 17
AppWidgetProvider lifecycle The action fired are the following: android.appwidget.action.appwidget_enabled When it is created the first instance of the AppWidget android.appwidget.action.appwidget_update When an update is needed: First load on screen and periodically (if selected) android.appwidget.action.appwidget_deleted When an instance of the AppWidget is deleted android.appwidget.action.appwidget_disabled When de last instance of the AppWidget is deleted Alberto Panizzo 18
AppWidgetProvider implementation public class ForecastsWidget extends AppWidgetProvider { @Override public void onupdate(context context, AppWidgetManager appwidgetmanager, int[] appwidgetids) {... //Got data to show.. for every instance of this AppWidget: for (int appwidgetid : appwidgetids) { //Generate the new graphic RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.forecasts_widget); views.settextviewtext(r.id.condition, condition); views.settextviewtext(r.id.day, day); views.settextviewtext(r.id.temp_high, "Max: "+temp_high); views.settextviewtext(r.id.temp_low, "Min: "+temp_low); views.setonclickpendingintent(r.id.condition, //Add actions on click PendingIntent.getActivity(context, 0, new Intent(context, ForecastsActivity.class), 0)); //Update the remote AppWidget appwidgetmanager.updateappwidget(appwidgetid, views); } } Alberto Panizzo 19
AppWidgetProvider implementation //In layout/forecasts_widget.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:background="@android:color/black" android:layout_margin="5dp" android:padding="6dp"> <include layout="@layout/forecast_item" /> </LinearLayout> //In layout/forecast_item.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="6dip" android:minheight="?android:attr/listpreferreditemheight"> <TextView android:id="@+id/condition" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentleft="true" android:layout_alignparenttop="true" android:text="condition" android:textappearance="?android:attr/textappearancelarge" />... Alberto Panizzo 20
AppWidgetProvider implementation //In xml/forecasts_widget_info.xml <?xml version="1.0" encoding="utf-8"?> <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:initiallayout="@layout/forecast_item" android:minwidth="300dp" android:minheight="?android:attr/listpreferreditemheight" android:updateperiodmillis="10000" /> //In AndroidManifest.xml <receiver android:name=".forecastswidget" android:label="forecasts"> <intent-filter > <action android:name="android.appwidget.action.appwidget_update" />... </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/forecasts_widget_info"/> </receiver> Alberto Panizzo 21
AppWidget more.. Refer to [3] to understand how: Create and bind a Configuration Activity launched by the AppWidgetHost when the widget is placed on the screen Manage the new Android 3.0+ AppWidgets collections Alberto Panizzo 22
Lecture 11 Sensors Interface Application's widgets Tip: How to catch memory leaks Alberto Panizzo 23
Debug memory allocations Two tools available: DDMS Allocation tracker Useful to have an idea of what is going on tracking the allocations done, within the given period. Heap dumps Snapshot of the full application's heap stored in a binary file called HPROF Alberto Panizzo 24
Allocation Tracker Alberto Panizzo 25
Allocation Tracker Gives the density of allocations in the period. More allocations you do, more frequent will execute the garbage collector blocking time ~200ms Alberto Panizzo 26
Heap analysis Heap status: Alberto Panizzo 27
Heap analysis If your App has a monotonic increasing heap size... Alberto Panizzo 28
Heap analysis To Dump the HPROF file: Alberto Panizzo 29
Heap analysis Android use a custom HPROF format. Convert to standard as follows: $ hprof-conv dump.hprof converted-dump.hprof Now you can analyze it using: Java Standard tool: jhat Eclipse Memory Analysis Tool (MAT) [5] Alberto Panizzo 30
Memory Analysis Tool (MAT) Histogram: shows the allocations per type: Alberto Panizzo 31
(MAT) who's referencing this obj? Right click on one item, list objects with incoming references Alberto Panizzo 32
Links of interest [1] http://developer.android.com/guide/topics/sensors/sensors_overview.html [2] http://developer.android.com/reference/android/appwidget/package-summary.html [3] http://developer.android.com/guide/topics/appwidgets/index.html [4] http://android-developers.blogspot.com/2011/03/memory-analysis-for-android.html [5] http://www.eclipse.org/mat/ Alberto Panizzo 33