Friday, April 15, 2011

Drawing on widget canvas

There are a lot of examples about android canvas. But how to be if we want to draw something in our widget?

Here is simple example how to do this using RemoteViews.

//create a remote view from widget layout
RemoteViews views = new RemoteViews(context.getApplicationContext().getPackageName(), R.layout.widget_layout);

//create a bitmap
bitmap = Bitmap.createBitmap(100, 100, Config.ARGB_8888);

//create a canvas from existant bitmap that will be used for drawing
Canvas canvas = new Canvas(bitmap);

Than we can use android canvas methods to draw all we want.

//create new paint
Paint p = new Paint(); 

//draw circle
canvas.drawCircle(50, 50, 7, p);

//set our bitmap to view
views.setImageViewBitmap(, bitmap);

Have a nice code!

Sunday, April 3, 2011

Registering a broadcast receiver from widget

A broadcast receiver is a class which extends "BroadcastReceiver" and which is registered as a receiver in an Android Application via the AndroidManifest.xml or via code.

BroadcastReceiver registration is quite simple for and application. This example will show you how to register it from widget.

Es an example we will register receiver for ACTION_TIME_TICK intent.

We do not need to register it on AndroidManifest.xml because ACTION_TIME_TICK intent can't be registered in manifest.

First of all you need to create a BroadcastReceiver class instance.

private BroadcastReceiver HelloReceiver = new BroadcastReceiver(){

     public void onReceive(Context context, Intent intent) {
          //do something on receive

Register our receiver in WidgetProvider class onUpdate method.

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetId) {
     context.getApplicationContext().registerReceiver(this.HelloReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
     //do other actions such as update widget... 

The main point of this example that we are using a context.getApplicationContext() method to get a context instead of context that passed to onUpdate()

Have a nice code!