Во-первых, в ваших WidgetProviderClass
вы должны определить свои действия, чтобы вы могли различать их. В этом случае:
private static final String ACTION_UPDATE_CLICK_NEXT = "action.UPDATE_CLICK_NEXT";
private static final String ACTION_UPDATE_CLICK_PREVIOUS = "action.UPDATE_CLICK_PREVIOUS";
Далее, в вашей переопределенной функции onUpdate()
вы должны поставить:
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.your_widget_layout);
views.setOnClickPendingIntent(R.id.nextButtonWidget, getPendingSelfIntent(context, ACTION_UPDATE_CLICK_NEXT));
views.setOnClickPendingIntent(R.id.previousButtonWidget, getPendingSelfIntent(context, ACTION_UPDATE_CLICK_PREVIOUS));
}
Функция для создания намерения, направленного на текущий класс (самому себе):
private PendingIntent getPendingSelfIntent(Context context, String action) {
Intent intent = new Intent(context, getClass()); // An intent directed at the current class (the "self").
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
При наступлении события onReceive()
будет вызвана функция:
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (ACTION_UPDATE_CLICK_NEXT.equals(intent.getAction())) {
// if the user clicked next
}
else if (ACTION_UPDATE_CLICK_PREVIOUS.equals(intent.getAction())) {
// if the user clicked previous
}
}
БОНУС:
Если вы хотите вызвать функцию onUpdate()
, то эта функция сделает это за вас. Требуется только параметр контекста!
/**
* A general technique for calling the onUpdate method,
* requiring only the context parameter.
*
* @author John Bentley, based on Android-er code.
* @see <a href="http://android-er.blogspot.com
* .au/2010/10/update-widget-in-onreceive-method.html">
* Android-er > 2010-10-19 > Update Widget in onReceive() method</a>
*/
private void onUpdate(Context context) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName thisAppWidgetComponentName = new ComponentName(context.getPackageName(), getClass().getName());
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidgetComponentName);
onUpdate(context, appWidgetManager, appWidgetIds);
}