How do I create events in a widget?


I intend to create a widget that would consist of a simple button that, when pressed, executes an action.

I've been watching tutorials like this " Widgets SGOliver " , I understand a lot of what they explain there but my problem comes in the part of the Intent and PendingIntent when adding action to a button.

Intent intent = new Intent("");
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);

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

controles.setOnClickPendingIntent(, pendingIntent);   

That code causes a button in the widget to update the information in the widget so that it does not have to wait for the automatic update of the widget.

I do not really understand where in the code the button is told to update the information.

I understand that an intent is created with the name of the action and it is passed to it as a parameter in the getBroadcasT() method, but I do not understand how the button understands that it must update the information (so to speak).

I know that I explain myself fatal but it would be a great help if you could guide me.

asked by GerardoAGL96 20.10.2016 в 00:27

2 answers


By putting an id on your button and using the function .setOnClickPendingIntent , you are referring to it in the following sentence:

controles.setOnClickPendingIntent(, pendingIntent); 

When you use you are actually referencing your button with id BtnActualizar within the project. Being the unique and unrepeatable id's, you know for sure that you are referring to your button.

That is, in reality, what your code is doing is wait until the button is pressed and launch the Intent, an event that you detect by setOnClickPendingIntent . Once the button has been pressed, the Intent is thrown.

answered by 20.10.2016 / 00:36

What you want to do is a Widget to execute an action when you press a button, simply create a custom layout for your Widget in which you would add a button:


<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android=""
    android:layout_height="match_parent" >

        tools:ignore="NewApi" />

        android:id="@+id/button" />


to get the button on your Widget:

To perform some action on the Widget , it is done by a type of Intent, the PendingIntent

Intent intent = new Intent(this, Activity2.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
updateViews.setOnClickPendingIntent(, pendingIntent);

Obviously for it to work you have to configure the receiver in the file Manifest.xml , appwidget-provider , etc ...

As an example, this project from a good friend, Mark Murphy (@CommonsWare)

answered by 20.10.2016 в 01:25