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
- 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”.
- Add internet permission
Open
AndroidManifest.xml(found underapp/src/main) and add this line just before the<application>tag:<uses-permission android:name="android.permission.INTERNET" />
- Design the layout
Open
res/layout/activity_main.xml. Replace the defaultTextViewwith a simple UI: aButtonfor “Toggle Light”, aSeekBarfor brightness, and aTextViewto 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> - Set up networking code
Create a new Kotlin class called
ApiClient.kt. UseHttpURLConnection(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. } } - Wire up the UI in MainActivity.kt
In
MainActivity.kt, find the views by ID and set click listeners. For the button, callsendCommand()with your device’s URL (e.g.,http://192.168.1.100/relay/0?turn=on). For the SeekBar, usesetOnSeekBarChangeListenerto send brightness changes. Show a toast or update the status TextView with the result. - 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. - 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.
- Add MQTT support (optional but recommended)
If your smart home uses MQTT, add the Eclipse Paho library to
build.gradledependencies. Create an MQTT client, connect to your broker (e.g.,tcp://192.168.1.50:1883), and publish to topics likehome/light/set. This is more reliable than HTTP for many setups. - Polish the UI
Add a dark theme, icons, and a more intuitive layout. Use Material Design components like
Switchfor toggles. You can also add multiple device controls by using aRecyclerView. - 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
SecurityExceptionif you forget to addINTERNETpermission. - Blocking the main thread – Network calls must be off the main thread; use coroutines or
AsyncTask(deprecated). Otherwise, the app freezes or throwsNetworkOnMainThreadException. - 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
SharedPreferencesso 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
onProgressChangedfires 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
- 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.
- 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.
- Do I need to root my phone? – No, this app works on stock Android.
- 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.
- 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.
- 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
- MacBook Charger Not Working? Fix It Now
- Fix Windows Cannot Be Installed to This Disk
- Zoom on iPhone & iPad: Host or Join a Meeting
- Fix iPhone SE 4 Unable to Activate: Step-by-Step
- Keep Important Emails From Getting Buried in iPhone Mail Categories
- How to Clear RAM on iPhone: Speed It Up