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..

http://www.coderzheaven.com/2012/06/07/create-widget-android/

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 “MyWidget.java” 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 {
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
		
	}
	@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 });
				}
				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.

Website Pin Facebook Twitter Myspace Friendfeed Technorati del.icio.us Digg Google StumbleUpon Premium Responsive

Leave a Reply

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