BDayWidget code snippets

satya - Saturday, December 10, 2011 10:47:21 AM

Start with the manifest file


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.androidbook.BDayWidget"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" 
                android:label="Birthday Widget">
<!--
**********************************************************
*  Widget Configuration Activity
********************************************************** 
 -->
<activity android:name=".ConfigureBDayWidgetActivity"
              android:label="Configure Birthday Widget">
    <intent-filter>
      <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
    </intent-filter>
</activity>
    
<!--
**********************************************************
*  Birthday Provider
********************************************************** 
 -->
<receiver android:name=".BDayWidgetProvider">
   <meta-data android:name="android.appwidget.provider"
          android:resource="@xml/bday_appwidget_provider" />
   <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
   </intent-filter>
</receiver>
    
    </application>
    <uses-sdk android:minSdkVersion="3" />
</manifest>

This is where you define your widget provider class and also the configuration activity.

satya - Saturday, December 10, 2011 10:50:11 AM

/res/xml/bday_appwidget_provider.xml: widget definition


<!-- /res/xml/bday_appwidget_provider.xml -->
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="150dp"
    android:minHeight="120dp"
    android:updatePeriodMillis="100000"
    android:initialLayout="@layout/bday_widget"
    android:configure="com.androidbook.BDayWidget.ConfigureBDayWidgetActivity"
    android:label="My Birthday widget"
    >
</appwidget-provider>

This is where you define the size, widget layout file, configuration activity etc.

satya - Saturday, December 10, 2011 10:51:48 AM

An example widget layout file


<?xml version="1.0" encoding="utf-8"?>
<!-- layout/bday_widget.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="150dp"
    android:layout_height="120dp"
    android:background="@drawable/box1"
    >
<TextView  
	android:id="@+id/bdw_w_name"
    android:layout_width="fill_parent" 
    android:layout_height="30dp" 
    android:text="Anonymous"
    android:background="@drawable/box1"
    android:gravity="center"
    />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="60dp"
    >
	<TextView  
		android:id="@+id/bdw_w_days"
	    android:layout_width="wrap_content" 
	    android:layout_height="fill_parent" 
	    android:text="0"
	    android:gravity="center"
	    android:textSize="30sp"
	    android:layout_weight="50" 
	    />
	<TextView 
	   android:id="@+id/bdw_w_button_buy"
	    android:layout_width="wrap_content" 
	    android:layout_height="fill_parent" 
	    android:textSize="20sp"
	    android:text="Buy"
	    android:layout_weight="50" 
	    android:background="#FF6633"
	    android:gravity="center"
	/>
</LinearLayout>
<TextView  
	android:id="@+id/bdw_w_date"
    android:layout_width="fill_parent" 
    android:layout_height="30dp" 
    android:text="1/1/2000"
    android:background="@drawable/box1"
    android:gravity="center"
    />
</LinearLayout>

satya - Saturday, December 10, 2011 10:55:56 AM

The provider class


public class BDayWidgetProvider extends AppWidgetProvider 
{
    private static final String tag = "BDayWidgetProvider";
    public void onUpdate(Context context, 
                        AppWidgetManager appWidgetManager, 
                        int[] appWidgetIds) 
   {
        Log.d(tag, "onUpdate called");
        final int N = appWidgetIds.length;
        Log.d(tag, "Number of widgets:" + N);
        for (int i=0; i<N; i++) 
        {
            int appWidgetId = appWidgetIds[i];
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }
    public void onDeleted(Context context, int[] appWidgetIds) 
    {
        Log.d(tag, "onDelete called");
        final int N = appWidgetIds.length;
        for (int i=0; i<N; i++) 
        {
            Log.d(tag,"deleting:" + appWidgetIds[i]);
            BDayWidgetModel bwm =
                BDayWidgetModel.retrieveModel(context, appWidgetIds[i]);
            bwm.removePrefs(context);
        }
    }
    @Override 
    public void onReceive(Context context, Intent intent) 
    { 
        final String action = intent.getAction(); 
        if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) 
        {
            Bundle extras = intent.getExtras();
            
            final int appWidgetId = extras.getInt 
                              (AppWidgetManager.EXTRA_APPWIDGET_ID, 
                               AppWidgetManager.INVALID_APPWIDGET_ID);
            
            if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) 
            { 
                this.onDeleted(context, new int[] { appWidgetId }); 
            } 
        } 
        else
        { 
            super.onReceive(context, intent); 
        } 
    }
    public void onEnabled(Context context) 
   {
        Log.d(tag, "onEnabled called");
        BDayWidgetModel.clearAllPreferences(context);
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(
                new ComponentName("com.ai.android.BDayWidget", 
                       ".BDayWidgetProvider"),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    }
    public void onDisabled(Context context) 
    {
        Log.d(tag, "onDisabled called");
        BDayWidgetModel.clearAllPreferences(context);
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(
                new ComponentName("com.ai.android.BDayWidget", 
                       ".BDayWidgetProvider"),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }
    private void updateAppWidget(Context context, 
                          AppWidgetManager appWidgetManager,
                           int appWidgetId) 
   {
        BDayWidgetModel bwm = 
            BDayWidgetModel.retrieveModel(context, appWidgetId);
        if (bwm == null)
        {
            Log.d(tag,"No widget model found for:" + appWidgetId);
            return;
        }
        ConfigureBDayWidgetActivity
            .updateAppWidget(context, appWidgetManager, bwm);
   }
}

satya - Saturday, December 10, 2011 10:58:34 AM

The configurator activity


public class ConfigureBDayWidgetActivity extends Activity 
{
    private static String tag = "ConfigureBDayWidgetActivity";
    private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_bday_widget);
        setupButton();
        
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID, 
                    AppWidgetManager.INVALID_APPWIDGET_ID);
        }
    }
    private void setupButton()
    {
       Button b = 
           (Button)this.findViewById(R.id.bdw_button_update_bday_widget);
       b.setOnClickListener(
             new Button.OnClickListener(){
                public void onClick(View v)
                {
                   parentButtonClicked(v);
                }
             });
       
    }
    private void parentButtonClicked(View v)
    {
        String name = this.getName();
        String date = this.getDate();
        if (Utils.validateDate(date) == false)
        {
            this.setDate("wrong date:" + date);
            return;
        }
        if (this.mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID)
        {
            Log.d(tag, "invalid app widget id");
            return;
        }
        updateAppWidgetLocal(name,date);
        Intent resultValue = new Intent();
        resultValue.putExtra(
                AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
        setResult(RESULT_OK, resultValue);
        finish();
    }
    private String getName()
    {
        EditText nameEdit = 
            (EditText)this.findViewById(R.id.bdw_bday_name_id);
        String name = nameEdit.getText().toString();
        return name;
    }
    private String getDate()
    {
        EditText dateEdit = 
            (EditText)this.findViewById(R.id.bdw_bday_date_id);
        String dateString = dateEdit.getText().toString();
        return dateString;
    }
    private void setDate(String errorDate)
    {
        EditText dateEdit = 
            (EditText)this.findViewById(R.id.bdw_bday_date_id);
        dateEdit.setText("error");
        dateEdit.requestFocus();
    }
    private void updateAppWidgetLocal(String name, String dob)
    {
        BDayWidgetModel m = 
            new BDayWidgetModel(mAppWidgetId,name,dob);
        updateAppWidget(this,
                AppWidgetManager.getInstance(this),m);
        m.savePreferences(this);
    }

    public static void updateAppWidget(Context context, 
            AppWidgetManager appWidgetManager,
            BDayWidgetModel widgetModel) 
    {
        RemoteViews views = new RemoteViews(context.getPackageName(), 
                      R.layout.bday_widget);
        
        views.setTextViewText(R.id.bdw_w_name
            , widgetModel.getName() + ":" + widgetModel.iid);
        
        views.setTextViewText(R.id.bdw_w_date
                , widgetModel.getBday());
        
        //update the name
        views.setTextViewText(
                R.id.bdw_w_days,Long.toString(widgetModel.howManyDays()));
        
        Intent defineIntent = new Intent(Intent.ACTION_VIEW, 
                Uri.parse("http://www.google.com"));
        PendingIntent pendingIntent = 
            PendingIntent.getActivity(context,
                        0 /* no requestCode */, 
                        defineIntent, 
                        0 /* no flags */);
        views.setOnClickPendingIntent(
                R.id.bdw_w_button_buy, pendingIntent);
        
        // Tell the widget manager
        appWidgetManager.updateAppWidget(widgetModel.iid, views);
    }
}