开发者

help for using appwidget with broadcastreceiver and service?

开发者 https://www.devze.com 2023-02-14 19:10 出处:网络
i have one widget in which there are two buttons and开发者_开发百科 one service class in which i have two methods on clikcing of button i want to call the methods in service class.

i have one widget in which there are two buttons and开发者_开发百科 one service class in which i have two methods on clikcing of button i want to call the methods in service class. any reference or code example? how can i do it?

thankx


I'm guessing that your question pertains to appWidgets. If not, the answer below will probably be less useful, although you can still adapt part of it to your own use, I think.

First declare some action(s), like this:

    public static final String ACTION_HIDE_GUIDE_OVERLAY = "dk.something.appwidget.calendar.guide.hide";

Use the action(s) to declare an Intent and a PendingIntent:

    Intent intent = new Intent(context, CalendarService.class);
    intent.setAction(CalendarService.ACTION_HIDE_GUIDE_OVERLAY);
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
    PendingIntent buttonPendingIntent1 = PendingIntent.getService(context, appWidgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT);

Then register the pendingIntent with the RemoteView for your widget:

    views.setOnClickPendingIntent(R.id.calendar_button_1, buttonPendingIntent1);

Finally, in the onStartCommand or onHandleIntent of your service, examine the action of the intent to determine which of your methods to call:

  if (intent.getAction().equals(CalendarService.ACTION_INITIALIZE_CALENDAR)) {
        int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
        onInitializeCalendar(appWidgetIds);
} else if (intent.getAction().equals(CalendarService.ACTION_HIDE_GUIDE_OVERLAY)) {
        int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        onHideGuideOverlay(appWidgetId);
} else ...

Note: The code snippets are taken almost directly from my Glass Widgets, so to adapt it to your own use, you would have to replace the action constant with your own two actions (one action for each button), replace R.id.calendar_button_1 with the actual id of one of your buttons, replace the CalendarService with the name of your own service class and the methods onInitializeCalendar and onHideGuideOverlay with the name of the two methods in your service class that you want to call.

If you only ever have one instance of your widget visible at one time, then you don't need to fiddle around with the appWidgetId, but you probably can't guarantee that. I have some settings that can vary from widget instance to widget instance, so I put the id of the appwidget that was clicked into the intent, where the service can get at it when servicing my request.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号