Daily #13: Diving Deeper Into Android Events: Location Tracking, Screen On/Off, Orientation Changes, Battery Status, Incoming Calls/SMS, and Pedometer

Welcome back to our daily tech series! Today, we're delving deeper into some essential Android events and features that you can implement in your apps to enhance user experience. Let's get started.

Location Tracking

Android provides the LocationManager for accessing system location services. This lets your app request location updates from GPS or network providers. Here's an example:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String bestProvider = locationManager.getBestProvider(criteria, true);

LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        // Do something with the location.
    }
    // Override other methods as needed
};

// Request location updates
locationManager.requestLocationUpdates(bestProvider, 0, 0, locationListener);

For more information, visit the Android developer's guide on location.

Screen On/Off

Android sends broadcast intents (Intent.ACTION_SCREEN_ON and Intent.ACTION_SCREEN_OFF) when the device's screen turns on and off. You can create a BroadcastReceiver to listen for these changes:

BroadcastReceiver screenStateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
            Log.i(TAG, "Screen turned on");
        } else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
            Log.i(TAG, "Screen turned off");
        }
    }
};

More details are available in the official Android developer guide on Broadcasts.

Orientation Changes

When a device's orientation changes, the system destroys and recreates the visible activity. You can handle such changes in your activity's lifecycle methods, particularly onConfigurationChanged:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Log.i(TAG, "Landscape");
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Log.i(TAG, "Portrait");
    }
}

See the Android developer's guide on handling runtime changes for more information.

Battery Level and Charging Status

By monitoring the battery level and charging status, your app can adapt its behavior to maintain a good user experience even under low battery conditions. Android broadcasts Intent.ACTION_BATTERY_CHANGED when the battery level or charging state changes:

BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                             status == BatteryManager.BATTERY_STATUS_FULL;
        // Do something with this info
    }
};

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(batteryReceiver, ifilter);

More details can be found in the [Android developer's guide on monitoring the battery level and charging state](https://developer.android

.com/training/monitoring-device-state/battery-monitoring).

Incoming Calls/SMS

If your app needs to be aware of incoming calls or SMS messages, Android provides TelephonyManager and PhoneStateListener:

TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
PhoneStateListener callStateListener = new PhoneStateListener() {
    public void onCallStateChanged(int state, String incomingNumber) {
        if (state == TelephonyManager.CALL_STATE_RINGING) {
            Log.i(TAG, "Incoming call: " + incomingNumber);
        }
    }
};
telephonyManager.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);

See the Android developer's guide on intercepting phone calls and receiving SMS messages for more information.

Pedometer

The Android platform provides a Step Counter sensor to track the number of steps the user has taken since the last device reboot. Here's a basic example:

SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if (countSensor != null) {
    sensorManager.registerListener(new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            int steps = (int)event.values[0];
            // Do something with this info
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // Handle accuracy changes
        }
    }, countSensor, SensorManager.SENSOR_DELAY_UI);
} else {
    Log.e(TAG, "Step Counter sensor not available!");
}

For more details, refer to the official Android Sensor documentation.

Network Changes

Keeping track of the network state is crucial for apps with online functionalities. You can use the ConnectivityManager to listen to network changes and adapt your app accordingly. For more details on handling network changes, refer to this post: "Daily#6 Understanding and Using ConnectivityManager".

Understanding and implementing these features can significantly enhance your app's functionality and user experience. Happy coding!

Comments

Popular posts from this blog

Daily#14. Understanding JVM, Dalvik, and ART: The Engines Behind Java and Android Applications

Daily#6. Understanding and Using NetworkCallback in Android

Learning Journey#5. From Foundation to Future: Cloud Computing as a Career Pathway