π Lecture 44 β Notifications, Widgets, Databases, and Detecting User Activity
π Overview: This lecture covers four major areas of Android development: creating and managing status bar notifications for background services, building home screen widgets with periodic updates, implementing persistent data storage using SQLite databases, and detecting user activity through device sensors and touch events. Understanding these topics is crucial for creating responsive, interactive, and data-driven mobile applications.
ποΈ Topics Covered
The lecture begins with status bar notifications for background services, including how to create, configure, and display notifications with sound, vibration, and lights. It then covers home screen widgets, their lifecycle, and update mechanisms. Next, it explains SQLite database creation, table management, data insertion, threading, and versioning. Finally, it explores detecting user activity through device orientation, accelerometer sensors, available sensor listing, touch events, gestures, and keyboard control.
π Lecture Summary
Notifications
A status bar notification adds an icon to the system's status bar with an optional ticker-text message and an expanded message in the "Notifications" window. When the user selects the expanded message, Android fires an Intent that usually launches an Activity. You can also configure the notification to alert the user with a sound, a vibration, and flashing lights on the device.
A status bar notification should be used for any case in which a background Service needs to alert the user about an event that requires a response. A background Service should never launch an Activity on its own; instead, it should create a status bar notification that will launch the Activity when selected by the user.
π Definition β Notification: defines the properties of your status bar notification, such as the status bar icon, the expanded message, and extra settings like sound to play.
π Definition β NotificationManager: an Android system service that executes and manages all Notifications.
To create a notification, you must retrieve a reference to the NotificationManager using getSystemService(), then pass your Notification object with notify():
// Get Reference to Notification Manager
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
// Instantiate the Notification
int icon = R.drawable.notification_icon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
// Define the Notification's expanded message and Intent
Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
// Pass the Notification to the NotificationManager
private static final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
Additional "fancy stuff" includes adding sound, vibration, and flashing lights to notifications.
π‘ Why this matters: Notifications allow background services to communicate with users without interrupting their current activity, which is essential for maintaining a good user experience.
Widgets
Widgets are little applications that can be placed on the home screen of an Android device. A widget gets its data on a periodic timetable. There are two methods to update a widget: one based on an XML configuration file and the other based on AlarmManager.
π Definition β AppWidgetProvider: a broadcast receiver that extends AppWidgetProvider and provides additional lifecycle hooks for widgets.
To create a widget, you must:
- Define a layout file for the widget
- Maintain an XML file (AppWidgetProviderInfo) describing widget properties
- Create a broadcast receiver extending AppWidgetProvider
- Maintain App Widget configuration in AndroidManifest.xml
- Optionally specify a configuration activity called once when a widget instance is added
To save power consumption, a widget does not have its own process but is part of the home screen process. The widget UI is created as a RemoteView, which can be executed by another process with the same permissions as the original application.
In the widget configuration file, you can specify a fixed update interval. The minimum update interval is 180000 milliseconds (30 minutes).
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:updatePeriodMillis="180000"
android:initialLayout="@layout/widget_layout"
android:minHeight="72dp"
android:minWidth="146dp">
</appwidget-provider>
The AppWidgetProvider class implements the onReceive() method, extracts required information, and calls widget lifecycle methods.
Creating Database / Persistence
Android incorporates SQLite (version 3), a server-less, transactional database engine. Inside the onCreate() method, you declare and assign an SQLiteDatabase:
SQLiteDatabase db;
db = openOrCreateDatabase("my_database.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
π Definition β openOrCreateDatabase(): a SQLiteDatabase method that takes a string name, an SQL mode, and a CursorFactory object. SQL modes include: CREATE_IF_NECESSARY, OPEN_READWRITE, OPEN_READONLY, and NO_LOCALIZED_COLLATORS.
To create a table, construct an SQL statement and execute it:
final String CREATE_TABLE_CITIES = "CREATE TABLE tb_cities (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"city_name TEXT);";
db.execSQL(CREATE_TABLE_CITIES);
To insert entries, use a ContentValues object:
ContentValues cv = new ContentValues();
cv.put("city_name", "Aberdeen");
db.insert("tb_cities", null, cv);
cv.put("city_name", "Dundee");
db.insert("tb_cities", null, cv);
Finally, close the database with db.close();
To make a database thread safe, use:
db.setLockingEnabled(true);
To version a database, use:
db.setVersion(2);
π‘ Why this matters: Persistent storage is essential for applications that need to save user data, preferences, or application state across sessions.
Detecting User Activity
Android handsets can detect speed, motion, gravitational pull, and the Earth's magnetic field. Combined with sensitive touch-screens capable of reading complex gestures, these input devices make smartphones versatile programming platforms.
Reading Device Orientation
To detect orientation changes, add a configChanges element to the <activity> node in AndroidManifest.xml, then override onConfigurationChanged():
@Override
public void onConfigurationChanged(Configuration config) {
super.onConfigurationChanged(config);
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
mTextView.setText("landscape");
} else if (config.orientation == Configuration.ORIENTATION_PORTRAIT) {
mTextView.setText("portrait");
}
}
Measuring Speed with Accelerometer To gather information from sensors, implement the SensorEventListener interface:
public class MotionDetector extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
// In onCreate():
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}
π Definition β SensorEventListener: an Android interface that provides callbacks for responding to changes in sensor values or accuracy.
Register the listener in onResume() and unregister in onPause():
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
The delay value controls how quickly the sensor operates and can dramatically affect power usage. The four settings are:
SENSOR_DELAY_FASTESTSENSOR_DELAY_GAMESENSOR_DELAY_NORMALSENSOR_DELAY_UI
The actual reading of accelerometer values occurs in onSensorChanged():
public void onSensorChanged(SensorEvent e) {
synchronized (this) {
if (e.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mTextView.setText("x= " + e.values[0] + "\ny= " + e.values[1] + "\nz= " + e.values[2]);
}
}
}
The accelerometer returns three values describing acceleration along each axis in m/sΒ².
The onAccuracyChanged() method must be included but can remain empty:
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
Possible accuracy constant values include: SENSOR_STATUS_ACCURACY_HIGH, SENSOR_STATUS_ACCURACY_MEDIUM, and SENSOR_STATUS_ACCURACY_LOW.
Other Types of Sensors
Available sensor types include: TYPE_ACCELEROMETER, TYPE_ALL, TYPE_GRAVITY, TYPE_GYROSCOPE, TYPE_LIGHT, TYPE_LINEAR_ACCELERATION, TYPE_MAGNETIC_FIELD, TYPE_ORIENTATION, TYPE_PRESSURE, TYPE_PROXIMITY, TYPE_ROTATION_VECTOR, and TYPE_TEMPERATURE.
Listing Available Sensors To detect which sensors are available on a device:
private SensorManager mSensorManager;
private TextView mTextView;
private List mList;
// In onCreate():
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mTextView = (TextView) findViewById(R.id.text_view);
mList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
for (int i = 1; i < mList.size(); i++) {
mTextView.append("\n" + mList.get(i));
}
Other Functionalities The lecture also mentions recognizing touch events, detecting multi-touch events, recognizing gestures, and controlling the on-screen keyboard.
β Key Takeaways
The most critical concepts from this lecture are: status bar notifications must be created from background Services (not Activities directly) using Notification and NotificationManager classes, with optional sound, vibration, and light alerts. Widgets are lightweight home screen components using RemoteViews with a minimum update interval of 30 minutes to conserve power. SQLite databases are created using openOrCreateDatabase(), tables are built with execSQL(), and data is inserted using ContentValues objects. Sensor detection requires implementing SensorEventListener, registering the listener in onResume() and unregistering in onPause() to manage battery consumption, with four delay settings controlling sensor update frequency.
π§ Quick Revision Questions
- What two classes are required to create a status bar notification, and how do you pass the notification to the system?
- What is the minimum update interval for an Android widget, and why is this enforced?
- What SQL mode flag creates a database if it doesn't already exist, and what other flags are available?
- How do you make a SQLite database thread-safe, and how do you version it?
- What are the four sensor delay settings and which one is most battery-efficient?