androidkotlinbroadcastreceiverappwidgetprovider

How to keep a socket connection alive in an Android home screen widget


I have a widget: class SmartAppWidget : AppWidgetProvider() in this class I open a bluetooth socket connection, but it always connects and disconnects, how do I keep the connection alive in home screen widget? any suggestions would be great. Thanks.

It's just a button that send commands over bluetooth when you click it:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialKeyguardLayout="@layout/smart_app_widget"
    android:initialLayout="@layout/smart_app_widget"
    android:minWidth="60dp"
    android:minHeight="60dp"
    android:updatePeriodMillis="86400000"
    android:configure="co.za.chester.smartcontroller.DeviceListActivity"
    android:widgetCategory="home_screen"></appwidget-provider>

Solution

  • An AppWidgetProvider is simply a manifest-registered subclass of BroadcastReceiver. By design, it does not stay alive — your AppWidgetProvider instance lives for a single call to onReceive() (and from there to onUpdate() or whatever).

    If you want to try to maintain a Bluetooth connection without an activity in the foreground, use a foreground service.