SoFunction
Updated on 2025-04-09

Simple steps to create a desktop widget for Android Widget

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

1. The first xml is a layout XML file (such as:), which is from this widget. Generally speaking, if you use this component to display the time, it will be OK to declare a textview in this layout XML.

2. The second xml is widget_provider.xml, which is mainly used to declare an appwidget. Among them, Layout is the one above.

3. The third xml is to register broadcastReceiver information.

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

2. Code cases

1. Define a WidgetProvider to handle some CallBacks of Widgets
(1) OnEnable, called when creating the first widget.
(2) OnDisable, contrary to OnEnable, create the last widget call.
(3) OnDelete, called when an instance of Widget is deleted.
(4) OnUpdate, called when the Widget needs to update its View.
(5) onReceive(): This method handles 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 = ;    // 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 = (context, 0, intent, 0);             
      RemoteViews views = new RemoteViews((), .widget_demo_layout);       
      (.wap_app, pendingIntent);        
      (appWidgetId, views);     
    }   
  } 
} 

2. Register in Provide

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

3. Create Widget configuration XML in the xml folder:

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

<appwidget-provider xmlns:andro 
  android:minWidth="60px" 
  android:minHeight="60px" 
  android:initialLayout="@layout/widget_demo_layout" 
  > 
</appwidget-provider> 

(4) Create a Layout of Widget

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:andro 
  android:orientation="vertical" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  > 
  <ImageView  
    android: 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:src="@drawable/icon"/> 
</LinearLayout>