How to get Notified when a widget is deleted?

By | June 10, 2012

I have already covered a tutorial on how to start with widgets and how to create a simple widget here..

Today I will show you how to get notified when a widget is deleted.

if you have already gone through my previous post, then there is only a small change in the “” file.

we have to add the onReceive() method to the class like this.

package com.coderzheaven.pack;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyWidget extends AppWidgetProvider {
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
	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,
				if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
					this.onDeleted(context, new int[] { appWidgetId });
				Toast.makeText(context, "Widget deleted", Toast.LENGTH_LONG).show();
			} else {
				super.onReceive(context, intent);

onReceive is always called before onUpdate is called. This code snipped checks the called action
and decides wheather to just run the receive method or the delete method.

I have already shown how to add a widget to the home screen, now for deleting simply press and hold the widget and drag to the delete icon on the bottom of the screen.

When you do this the onReceive() method will be called and a toast will appear saying “Widget Deleted”.

Widgets Android

You can download the complete android source code of the above post from here.

Please leave your valuable comments on this post.

One thought on “How to get Notified when a widget is deleted?

  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 *