Placing Controls in a Widget in Android and Listening to the events from them.

By | June 15, 2012

Hello everyone..

I have already shown how to create a simple widget and add it to the home screen in my previous posts. If you have missed these posts please check it here.

How to create a widget in android?

In the next post I showed you how to listen to a widget delete action and delete the widget.

Now in today’s tutorial I am going to show how to place controls like buttons inside the widget and listen to their events and respond to it.

I am proceeding the same as the previous tutorials.

First I will create a new project named “ControlsInWidget” and name the activity “MyActivity.java”.

Now we will create a layout for this main activity. settings.xml

These are the contents of settings.xml

<TableLayout android:id="@+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:id="@+id/tv1"
	android:text="CoderzHeaven Widget Settings Activity"
	android:textColor="@android:color/white"
	android:textSize="15dip"
	android:textStyle="bold"
	android:layout_marginTop="5dip"/>
</TableLayout>

This is the MyActivity. java that uses “settings.xml”

package com.coderzheaven.widgetpack;

import android.app.Activity;
import android.os.Bundle;

public class MyActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);
	}	
}

Now we will create the class for the widget which is named “MyWidget.java”.
please follow the instructions in the link while creating this class for the widget.

How to create a widget in android?

Now replace the contents inside MyWidget.java with this one.

package com.coderzheaven.widgetpack;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

public class MyWidget extends AppWidgetProvider {
	
	public static String WIDGET_SETTINGS_ACTION = "SettingsForWidget";
	public static String WIDGET_RECEIVER_ACTION = "WidgetActionReceiver";
	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
		
		Log.d("DEBUG","onUpdate");
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
		Intent configIntent = new Intent(context, MyActivity.class);
		configIntent.setAction(WIDGET_SETTINGS_ACTION);
		Intent active = new Intent(context, MyWidget.class);
		active.setAction(WIDGET_RECEIVER_ACTION);
		active.putExtra("Message", "Message for Button 1");
		PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
		PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);
		remoteViews.setOnClickPendingIntent(R.id.button_one, actionPendingIntent);
		remoteViews.setOnClickPendingIntent(R.id.button_two, configPendingIntent);
		appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		final String action = intent.getAction();
		if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
			final int appWidgetId = intent.getExtras().getInt(
			AppWidgetManager.EXTRA_APPWIDGET_ID,
			AppWidgetManager.INVALID_APPWIDGET_ID);
		if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
			this.onDeleted(context, new int[] { appWidgetId });
			}
		} else {
		// check, if our Action was called
		if (intent.getAction().equals(WIDGET_RECEIVER_ACTION)) {
			String msg = "";
			try {
				msg = intent.getStringExtra("Message");
			} catch (NullPointerException e) {
				Log.e("Error", "No Message");
			}
			PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
			NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
			Notification noty = new Notification(R.drawable.icon, "Button in the Widget Clicked.",System.currentTimeMillis());
			noty.setLatestEventInfo(context, "Notification from Widget", msg, contentIntent);
			notificationManager.notify(1, noty);
		}
		super.onReceive(context, intent);
		}
	}
}

Here we have two actions “WIDGET_SETTINGS_ACTION” and “WIDGET_RECEIVER_ACTION” which will be set as action for the two buttons inside the widget.

Now here is the main.xml which is the layout for the widget that contains the controls.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent"
	android:orientation="horizontal"
	android:background="@drawable/yellow_bkg"
	android:layout_gravity="center"
	android:layout_height="wrap_content">
<Button 
	android:text="Button1" 
	android:id="@+id/button_one"
	android:layout_weight="1"
	android:layout_gravity="center_horizontal|center"
	android:layout_height="fill_parent"
	android:layout_width="fill_parent"/>
<Button 
	android:text="Button2" 
	android:id="@+id/button_two"
	android:layout_weight="1"
	android:layout_gravity="center_horizontal|center"
	android:layout_height="fill_parent"
	android:layout_width="fill_parent"/>
</LinearLayout>

Widget

If you want the time to be updated every second, your have to modify simple_widget.xml
file and set updatePerdiodMillis to 1000.
The android update 1.6 unfortunately does not support any update periode that is less then 30
minutes.

Please go through this tutorial for setting up the xml for the widget.

How to create a widget in android?

Inside the onReceive we are checking this to ensure which button is clicked. You can write anything inside this function – like a http call or something to update the widget.

if (intent.getAction().equals(WIDGET_RECEIVER_ACTION)) {

}

The second button in the widget launches the activity “MyActivity” and the first one send a notification and doesn’t have a user interface.

Widget

Widget

Widget

You can download the complete eclipse java android source code from here.

Please leave your comments on this post and also share it and like it if this post was useful.

One thought on “Placing Controls in a Widget in Android and Listening to the events from them.

  1. Pingback: Handling Multiple Instances of a Widget in Android and Identifying each instance with it's own ID.

Leave a Reply

Your email address will not be published. Required fields are marked *