Simple steps to create the Android Widget desktop widget

  • 2021-06-28 13:52:13
  • OfStack

1. Widget design steps
Three XMLs and one class need to be modified:

1. The first xml is the layout XML file (e.g. main.xml), which is from this widget.1 Generally speaking, if you use this part to display time, then only one textview is declared as OK in this layout XML.

2. The second xml is widget_provider.xml, used primarily to declare an appwidget.Layout is the one specified above.

3. The third xml is AndroidManifest.xml, registering broadcastReceiver information.

4. The last class is used to do some business logic operations.Let it inherit class AppWidgetProvider.There are many methods in AppWidgetProvider, 1 Generally we just override the onUpdate (Context, AppWidgetManager, int[]) method.

2. Code Cases

1. Define an WidgetProvider to handle some CallBacks of Widget
(1) OnEnable, called when the first Widget is created.
(2) OnDisable, as opposed to OnEnable, creates the last Widget call.
(3) Called when an instance of OnDelete, Widget, is deleted.
(4) OnUpdate, called when Widget needs to update its View.
(5) onReceive (): This method handles the BroadcastReceiver behavior by default and calls the above method.

public class WidgetDemoAppWidgetProvider extends AppWidgetProvider{ 
  public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { 
    final int N = appWidgetIds.length;    // Perform this loop procedure for each App Widget that belongs to this provider     
    for (int i=0; i<N; i++) {       
      int appWidgetId = appWidgetIds[i];             
      Intent intent = new Intent();       
      PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);             
      RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_demo_layout);       
      views.setOnClickPendingIntent(, pendingIntent);        
      appWidgetManager.updateAppWidget(appWidgetId, views);     

2. Register Provide at AndroidManifast.xml

<receiver android:name="WidgetDemoAppWidgetProvider"> 
    <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> 
  <meta-data android:name="android.appwidget.provider" 
    android:resource="@xml/widget_demo_appwidget_info" /> 

3. Create the Widget configuration XML under the xml folder:

<?xml version="1.0" encoding="utf-8"?>

<appwidget-provider xmlns:android="" 

(4) Create Layout of Widget

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="" 

Related articles: