Search code examples
androidandroid-widget

Button click event for android widget


I have an android widget that fetches data from a server every 10 minutes and display's it on the screen.
I'd like to add a "Refresh" button to that widget.
When the user clicks that button I'd like to run the method that fetches the information from the server.
Adding an event handler to a button in an application is very easy, however I couldn't find an example for a widget.
I'd like to get some help with adding a function to a button click in a widget.


Solution

  • I found out how to do that.
    Add an action to the AndroidManifest.xml file in the > <receiver><intent-filter> tag:

    <action android:name="MY_PACKAGE_NAME.WIDGET_BUTTON" />
    

    In the provider add a constant that matches the action name:

    public static String WIDGET_BUTTON = "MY_PACKAGE_NAME.WIDGET_BUTTON";
    

    In the onUpdate() method add a pending intent that matches the action:

    Intent intent = new Intent(WIDGET_BUTTON);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    views.setOnClickPendingIntent(R.id.MY_BUTTON_ID, pendingIntent );
    

    Finally, in the onRecieve() method, check the action name:

     if (WIDGET_BUTTON.equals(intent.getAction())) {
    //your code here
    
        }