Charge Alert: Alarm for Unplugged Devices in Android Kotlin Version

In this tutorial, you will learn how to develop an Android application using Kotlin that alerts the user with an alarm sound when the device is unplugged from the charger. The tutorial will guide you through implementing a BroadcastReceiver to monitor changes in the power connection status, specifically detecting when the charger is disconnected. You'll set up logic to trigger an alarm or notification upon detecting this event, ensuring users are promptly informed when the device is unplugged from its power source. By following this step-by-step guide, you'll gain practical experience in handling broadcast events, managing alarms or notifications, and enhancing user awareness of device power status in your Kotlin-based Android applications.
Submitted on July 07, 2024

To create an Android app that alerts the user with an alarm sound when the device is unplugged from the charger, you'll need to monitor the power connection status using a BroadcastReceiver and trigger an alarm when the charger is disconnected. Here's a step-by-step guide to implement this in Kotlin:

Step-by-Step Implementation

1. Add necessary permissions and dependencies:

  • Ensure the following permissions are added to your ‘AndroidManifest.xml‘ file:

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.VIBRATE"/>
    
  • You may also want to add a sound file (e.g., ‘alarm_sound.mp3’) to the ‘res/raw’ directory for the alarm sound.

2. Modify activity_main.xml

  • You can keep it simple with just a blank layout since most of the work will be done programmatically.

3. Implement MainActivity.kt


package com.example.batteryalarm

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.PowerManager
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    private lateinit var mediaPlayer: MediaPlayer
    private lateinit var powerConnectionReceiver: PowerConnectionReceiver

    @Override
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Initialize MediaPlayer with alarm sound
        mediaPlayer = MediaPlayer.create(this, R.raw.alarm_sound)

        // Initialize and register power connection receiver
        powerConnectionReceiver = PowerConnectionReceiver()
        val filter = IntentFilter()
        filter.addAction(Intent.ACTION_POWER_CONNECTED)
        filter.addAction(Intent.ACTION_POWER_DISCONNECTED)
        registerReceiver(powerConnectionReceiver, filter)
    }

    @Override
    override fun onDestroy() {
        super.onDestroy()
        // Release resources
        mediaPlayer.release()
        unregisterReceiver(powerConnectionReceiver)
    }

    inner class PowerConnectionReceiver : BroadcastReceiver() {
        @Override
        override fun onReceive(context: Context?, intent: Intent?) {
            when (intent?.action) {
                Intent.ACTION_POWER_CONNECTED -> {
                    // Charger connected
                    Toast.makeText(context, "Charger connected", Toast.LENGTH_SHORT).show()
                }
                Intent.ACTION_POWER_DISCONNECTED -> {
                    // Charger disconnected, play alarm
                    Toast.makeText(context, "Charger disconnected", Toast.LENGTH_SHORT).show()
                    playAlarm()
                }
            }
        }
    }

    private fun playAlarm() {
        if (!mediaPlayer.isPlaying) {
            mediaPlayer.isLooping = true
            mediaPlayer.start()
        }
    }
}

    
  • Open ‘MainActivity.kt’ and implement the logic to monitor charger status and trigger an alarm when the charger is disconnected.

Explanation:

  • MainActivity.kt:
    • ‘onCreate()’: Initializes MediaPlayer with the alarm sound (‘R.raw.alarm_sound.mp3’).
    • Registers a ‘PowerConnectionReceiver’ to listen for ‘ACTION_POWER_CONNECTED’ and ‘ACTION_POWER_DISCONNECTED’ broadcasts.
    • ‘PowerConnectionReceiver’: Inner class that extends BroadcastReceiver. It overrides ‘onReceive()’ to handle power connection events:
      • When ‘ACTION_POWER_CONNECTED’ is received, it shows a toast message.
      • When ‘ACTION_POWER_DISCONNECTED’ is received, it shows a toast message and calls ‘playAlarm()’ to start playing the alarm sound.
    • ‘playAlarm()’: Starts playing the alarm sound using MediaPlayer if it's not already playing.

Testing:

  • Run the app on an emulator or a physical device.
  • Connect and disconnect the charger to observe the app's behavior:
    • When the charger is disconnected (‘ACTION_POWER_DISCONNECTED’), the app displays a toast message and plays the alarm sound (‘alarm_sound.mp3’).

This implementation provides a basic example of how to create an Android app that alerts the user with an alarm sound when the device is unplugged from the charger.