Using sendBroadcast to update Android widgets

I am creating an appwidget that needs to be updated when some changes in the application database. What am I doing: 1. Create a working widget 2. Override the onReceive method:

public static final String DATABASE_CHANGED = " utimetable.DATABASE_CHANGED";
@Override
public void onReceive(Context context, Intent intent) 
{
    String action = intent.getAction();
    if (action.equals(DATABASE_CHANGED) || action.equals(Intent.ACTION_DATE_CHANGED)) 
    {
        AppWidgetManager gm = AppWidgetManager.getInstance(context);
        int[] ids = gm.getAppWidgetIds(new ComponentName(context, widget_provider.class));
        this.onUpdate(context, gm, ids);            
    }
    else 
    {
        super.onReceive(context, intent);
    }
}
  • In AndroidManifest:

        <receiver android:name=".widget_provider" android:label="@string/widget_today_name">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            <action android:name="utimetable.DATABASE_CHANGED" />
            <action android:name="android.intent.action.DATE_CHANGED" />
        </intent-filter>
        <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_row" />
    </receiver>
    
  • Add broadcast messages to all database change functions:

    public static void sendUpdateIntent(Context context) 
    {
        Intent i = new Intent(context, widget_provider.class);
        i.setAction(widget_provider.DATABASE_CHANGED);
        context.sendBroadcast(i);
    }
    

But the widget is still not updating when I make changes to the database. What should I do?

+3
source share
1 answer

just guessing by looking at your code, but this space after the first “looks wrong”

.... DATABASE_CHANGED = " utimetable.DATABASE_CHANGED";
+2
source

Source: https://habr.com/ru/post/1790458/


All Articles