简体   繁体   中英

How to broadcast an intent to a specific appwidget?

I am creating a appwidget which needs to update on a specific interval. I use AlarmManager for this.

I want to have the alarm run the onUpdate() method in the AppWidgetProvider .

    //Create the intent
    Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);              

    //Schedule the alarm        
    AlarmManager manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    manager.setRepeating(AlarmManager.RTC, startAlarmCal.getTime().getTime(), 1000 * 60, pendingIntent);

However, this intent causes all the widget's to update. I want to somehow only send this intent to my own appwidget. How would I do this?

Use a custom Intent to send to your widgets. You can register them in the manifest.xml. You cannot update specif widget ids but types of widget if you have many different ones.

<receiver
        android:name=".widget.WidgetProvider"
        android:label="1x1">
        <service
            android:name=".extra.WidgetProvider$WidgetUpdateService1x1" />
        <intent-filter>
            <action
                android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            <action
                android:name="nitro.blub.APPWIDGET_MANUEL_UPDATE" />
        </intent-filter>
        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/widget_info" />

    </receiver>

You might try adding this(slightly modified to suit your needs, of course):

// Change the text in the widget
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.main);
ComponentName thisWidget = new ComponentName(context, [Calling_class].class);

// Run update code here. e.g: //////////////
updateViews.setTextViewText(R.id.text, now);
////////////////////////////////////////////

appWidgetManager.updateAppWidget(thisWidget, updateViews);

Hope this helps.

Once again, it's all in the documentation :

updatePeriodMillis How often, in milliseconds, that this AppWidget wants to be updated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM