Search code examples
androidandroid-pendingintentandroid-remoteview

Android - Attach a click listener to a RemoteViews


Suppose I have created an instance of RemoteViews and it contains two Buttons. I want when user clicks these buttons a Service (or a BroadcastReceiver or something else ) handles this click. As I know so far, there is two ways for achieve this purpose :

  1. Assign different Actions to these Buttons for example
    ACTION_BTN_1_CLICKED
    and
    ACTION_BTN_2_CLICKED
    and then retrieve the action in the Service via intent.getAction() and finally service does a appropriate task

  2. Put some extra into the Intent object which is enclosed via PendingIntent for example:

    intent.putStringExtra("which_button", "btn1"); // for Button 1
    and
    intent.putStringExtra("which_button", "btn2"); // for Button 2

    In the other hand in Service I can distinguish this signal via intent.getExtras().getString("which_button")

Now my question is which approach is better at least in practice? Thanks


Solution

  • I'm not sure you can argue one being better than another, but I think the second solution might be more manageable and extendable. You could put an Integer extra, perhaps IDs that you declare in the R class. This ensures that they are unique and allows you to reference them in switch statement. It also means your routing code is in one place, so if there is a bug there it will be easier to find.