Search code examples
androidandroid-intentwidgetandroid-pendingintent

Widget that executes code on onclick


I want to execute a code when the icon of the widget is clicked.
The widget does have this layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:layout_margin="8dip" >
    <ImageView
        android:id="@+id/update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="4dip"
        android:src="@drawable/ic_widget" />
</LinearLayout>

I need to executes a code when the ImageView is clicked.
This is the code of the Widget:

public class MyWidget extends AppWidgetProvider {

    private static final String WIDGET_BUTTON = "MyWidget.WIDGET_BUTTON";

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                         int[] appWidgetIds) {

        RemoteViews remoteViews =
                new RemoteViews( context.getPackageName(), R.layout.widget );
        remoteViews.setImageViewResource(R.id.update, R.drawable.ic_widget);

        ComponentName myWidget =
                new ComponentName(context, Button.class);

        Intent intent = new Intent(context, SecurityWidget.class);
        intent.setAction(WIDGET_BUTTON);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        remoteViews.setOnClickPendingIntent(R.id.update, pendingIntent);
        appWidgetManager.updateAppWidget( myWidget, remoteViews);
    }

    @Override
    public void onReceive(Context context, Intent intent)
    {
        super.onReceive(context, intent);

        if (WIDGET_BUTTON.equals(intent.getAction())) {
            //your code here
            Toast.makeText(context, "EXAMPLE, Toast.LENGTH_LONG).show();
        }
    }
}

This is how the widget is created in the AndroidManifest:

<receiver
        android:icon="@drawable/ic_widget"
        android:label="My Widget"
        android:name="MyWidget" >
        <intent-filter >
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            <action android:name="MyWidget.WIDGET_BUTTON" />
        </intent-filter>

        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/widget_info" />
    </receiver>

It does not work. The "onReceive" code is fired only when I add or I remove the widget from the home screen.


Solution

  • Should this not be MyWidget.class in place of Button.class?

    ComponentName myWidget =
                    new ComponentName(context, Button.class);