How to create android app with app widget in single application

前端 未结 2 1110
终归单人心
终归单人心 2020-12-02 08:13

I have already done one android application which stores date with person name and phone number.

Now I have to develop one widget f

2条回答
  •  悲哀的现实
    2020-12-02 08:59

    Create and configure widget

    To register a widget you create a BroadcastReceiver with an intent filter for the android.appwidget.action.APPWIDGET_UPDATE action.

    
           
                
           
    
           
     
    

    You also specify the meta-data for the widget via the android:name="android.appwidget.provider attribute. The configuration file referred by this meta-data contains the configuration settings for the widget. If contains for example the update interface, the size and the initial layout of the widget.

    Create a new file myshape.xml in the /res/drawable directory. This file will define the background we use in your widget.

    
    
    
        
    
        
    
        
    
     
    

    Define the following widget_layout.xml file under the res/layout folder.

    
        
    
            
            
    
         
    

    now make the class.

    public class MyWidgetProvider extends AppWidgetProvider {
    
      private static final String ACTION_CLICK = "ACTION_CLICK";  
    
         @Override
      public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    
        // Get all ids
        ComponentName thisWidget = new ComponentName(context,
            MyWidgetProvider.class);
        int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
        for (int widgetId : allWidgetIds) {
          // Create some random data
          int number = (new Random().nextInt(100));
    
          RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
              R.layout.widget_layout);
          Log.w("WidgetExample", String.valueOf(number));
          // Set the text
          remoteViews.setTextViewText(R.id.update, String.valueOf(number));
    
          // Register an onClickListener
          Intent intent = new Intent(context, MyWidgetProvider.class);
    
          intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
          intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
    
          PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
              0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
          remoteViews.setOnClickPendingIntent(R.id.update, pendingIntent);
          appWidgetManager.updateAppWidget(widgetId, remoteViews);
        }
      }
    

提交回复
热议问题