sodcalculator

10 Tech How-To

How to Make an Android App for Your Smart Home

Guide 10-51187 · Updated · Step by step

This guide walks you through building a simple Android app that controls smart home devices—like lights, plugs, or thermostats—using Android Studio. You’ll create a user interface with buttons and sliders, connect to a local server (like a Raspberry Pi running MQTT or a custom HTTP API), and send commands to your devices. By the end, you’ll have a working app you can install on your phone and extend with more features.

What You’ll Need

  • Android Studio installed (latest stable version recommended)
  • An Android device or emulator (API 21 or higher)
  • Basic knowledge of Java or Kotlin (Kotlin is used here)
  • A smart home hub or device that exposes an HTTP API or MQTT broker (e.g., Home Assistant, Tasmota, or a custom ESP8266)
  • Your device’s IP address or hostname and the API endpoint details

Step-by-Step

  1. Create a new Android Studio project

    Open Android Studio and click “New Project”. Choose “Empty Views Activity” (or “Empty Activity” if using Compose). Name your app (e.g., “SmartHomeController”), select Kotlin as the language, and choose a minimum SDK of API 21 or higher. Click “Finish”.

  2. Add internet permission

    Open AndroidManifest.xml (found under app/src/main) and add this line just before the <application> tag:

    <uses-permission android:name="android.permission.INTERNET" />
  3. Design the layout

    Open res/layout/activity_main.xml. Replace the default TextView with a simple UI: a Button for “Toggle Light”, a SeekBar for brightness, and a TextView to show status. Example:

    <LinearLayout ...
        android:orientation="vertical"
        android:padding="16dp">
        <Button
            android:id="@+id/btnToggle"
            android:text="Toggle Light" />
        <SeekBar
            android:id="@+id/seekBrightness"
            android:max="100" />
        <TextView
            android:id="@+id/tvStatus"
            android:text="Ready" />
    </LinearLayout>
  4. Set up networking code

    Create a new Kotlin class called ApiClient.kt. Use HttpURLConnection (or a library like OkHttp) to send GET/POST requests. For simplicity, use a coroutine to avoid blocking the main thread. Example function:

    suspend fun sendCommand(url: String, method: String) {
        withContext(Dispatchers.IO) {
            val connection = URL(url).openConnection() as HttpURLConnection
            connection.requestMethod = method
            connection.connect()
            // Check response code, read response, etc.
        }
    }
  5. Wire up the UI in MainActivity.kt

    In MainActivity.kt, find the views by ID and set click listeners. For the button, call sendCommand() with your device’s URL (e.g., http://192.168.1.100/relay/0?turn=on). For the SeekBar, use setOnSeekBarChangeListener to send brightness changes. Show a toast or update the status TextView with the result.

  6. Handle local network security

    Android blocks cleartext traffic by default on API 28+. If your device uses HTTP (not HTTPS), add android:usesCleartextTraffic="true" to the <application> tag in the manifest, or better, create a network security config that allows cleartext only for your local IP range.

  7. Build and run

    Connect your phone via USB (enable Developer Options and USB debugging) or start an emulator. Click the green “Run” button. The app should install and launch. Test the button and slider.

  8. Add MQTT support (optional but recommended)

    If your smart home uses MQTT, add the Eclipse Paho library to build.gradle dependencies. Create an MQTT client, connect to your broker (e.g., tcp://192.168.1.50:1883), and publish to topics like home/light/set. This is more reliable than HTTP for many setups.

  9. Polish the UI

    Add a dark theme, icons, and a more intuitive layout. Use Material Design components like Switch for toggles. You can also add multiple device controls by using a RecyclerView.

  10. Test thoroughly

    Test on a real device, not just an emulator, because network behavior differs. Check that the app handles device disconnects gracefully (e.g., show a “Connection lost” message).

Common Mistakes

  • Missing internet permission – The app crashes with a SecurityException if you forget to add INTERNET permission.
  • Blocking the main thread – Network calls must be off the main thread; use coroutines or AsyncTask (deprecated). Otherwise, the app freezes or throws NetworkOnMainThreadException.
  • Wrong IP address – Double-check that your device is on the same Wi-Fi network and the IP is correct. Use a static IP for the smart home device to avoid changes.
  • Cleartext traffic blocked – Forgetting to allow HTTP traffic results in a “Cleartext not permitted” error on Android 9+.
  • Not handling timeouts – If the device is offline, the app may hang. Set connect/read timeouts (e.g., 5000 ms) and catch exceptions.

Tips

  • Use a library like Retrofit for HTTP APIs—it simplifies JSON parsing and error handling.
  • For MQTT, consider using HiveMQ or Eclipse Paho; they have good Android support.
  • Store the device IP in SharedPreferences so users can change it without recompiling.
  • Add a “Refresh” button to query device status and update the UI accordingly.
  • Test with a free app like “MQTT Dashboard” to verify your broker is working before coding.

Troubleshooting

  • App crashes on launch – Check Logcat in Android Studio for stack traces. Common causes: missing permission, invalid layout ID, or null pointer. Fix accordingly.
  • Network request fails – Verify the device IP with a browser (open the URL in Chrome). If it works, check your code for typos. If it doesn’t, the device may be off or firewalled.
  • “Cleartext not permitted” error – Add android:usesCleartextTraffic="true" or configure a network security config.
  • UI freezes – Ensure you’re using coroutines or threads for network calls. Never call sendCommand() directly from the main thread.
  • SeekBar changes don’t work – The onProgressChanged fires continuously; debounce the network call (e.g., only send when user stops moving) to avoid flooding the device.
  • App works on emulator but not on phone – The emulator uses 10.0.2.2 for the host machine; your phone needs the real LAN IP. Also, ensure both are on the same Wi-Fi.

Frequently Asked Questions

  1. Can I control devices without a hub? – Yes, if your device has a local HTTP API (like Tasmota or ESPHome). You just send HTTP requests directly.
  2. Is MQTT better than HTTP? – For many devices, MQTT is more reliable and uses less bandwidth, especially for frequent status updates. HTTP is simpler for basic on/off commands.
  3. Do I need to root my phone? – No, this app works on stock Android.
  4. Can I use this app outside my home network? – Not directly. You’d need to set up port forwarding or a VPN, but that raises security risks. Better to use a cloud bridge like Home Assistant’s remote access.
  5. How do I add more devices? – Create a list of devices in your code, or use a RecyclerView to display multiple controls. Each device needs its own endpoint.
  6. What if my device uses HTTPS with a self-signed certificate? – You’ll need to configure SSL trust in your app or use a library like OkHttp with a custom trust manager. This is advanced; consider using HTTP locally instead.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →