android widget id only for current widget

社会主义新天地 提交于 2019-12-08 02:15:24

问题


Can I get my current widgetId inside onUpdate() method of AppWidgetProvider?

I found many posts about sending appWidgetId in field of Intent, but I can't understand where I have to get it before sending.

I didn't find the methods for getting only current widget Id without configuration activities.


回答1:


try in onUpdate

    int a = appWidgetIds.length; 

If this returns 1, then:

    int yourAppWidgetId = appWidgetIds[0];

should return your appWidgetId.

EDIT

without seeing any code it´s difficult to give You the right answer, but I will give You an example. If you created your RemoteViews for your widgets, you have to create an intent for every RemoteView. At this intent, You could set an ID, for example:

    RemoteViews remoteViews = new RemoteViews(getApplicationContext()
                .getPackageName(), 
                    layout.your_widget_layout);

        Intent intent1 = new Intent(getApplicationContext(),
                YourAppWidgetProvider.class);

    intent1.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent1.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,widgetIds);
        intent1.putExtra("ID", "one");

Then create a PendingIntent, which You can set to remoteViews:

    PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getApplicationContext(), 1, intent1,
                PendingIntent.FLAG_ONE_SHOT);

    remoteViews.setOnClickPendingIntent(R.id.your_widget_button_id_in_xml,
                pendingIntent);

If user pressed the widget, you can get id inside onReceive() with

    String a = intent.getStringExtra("ID");

But this is only an incomplete example, there is a lot more to do. I think it is a good way, if you read this tutorial:

http://www.android10.org/index.php/articlesgeneralprogramming/315-app-widgets-tutorial

There is a good example with an updateService.



来源:https://stackoverflow.com/questions/13534421/android-widget-id-only-for-current-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!