You’ll need to create the widget itself in native code but you’ll also likely need to use Capacitor to set the data used by the widget as well as to trigger a widget refresh anytime you update it.
I used this plugin for iOS and it worked nicely. For Android I had to use custom code and it was more complicated, but that’s partially because I used an Android ListView in the widget.
There is also this Capacitor plugin that supports iOS and Android but I haven’t tried it.
It’s been several months since I made it so I’m rusty on the exact details but basically…
Create the widget itself in native Android code, and get the data to display from SharedPreferences.
In the Ionic app, use the @capacitor/preferences plugin to update the data in SharedPreferences as needed. Then use the capacitor-android-intents plugin’s ‘sendBroadcastIntent’ function when you need to trigger a widget update
In the Android native app’s MainActivity.java, add a BroadcastReceiver the refreshes the widget when it receives the BroadcastIntent mentioned above.
public class MainActivity extends BridgeActivity {
private BroadcastReceiver broadcastReceiver;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.myDomain.myApp.ACTION_REFRESH_WIDGET");
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// If the BroadcastIntent matches the one for refreshing the app's widgets then refresh
if ("com.myDomain.myApp.ACTION_REFRESH_WIDGET".equals(intent.getAction())) {
Log.d("MainActivity", "BroadcastIntent for widget refresh received. Intent is: " + String.valueOf(intent));
// Code to refresh widget
}
}
};
registerReceiver(broadcastReceiver, intentFilter);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
// Other MainActivity code…
}
Honestly I found it all pretty complicated and it took a long time to implement. I would take a good look at the second Capacitor plugin I mentioned in the previous post and see what it can do for you.