I'm trying to create an app widget that, when pressed, triggers a background job that saves time+location to a database.
From what I have been able to gather so far, the setup I probably want consists of an AppWidgetProvider subclass whose onUpdate() is responsible for setting up a PendingIntent on a RemoteView representing the widget button. Its onReceive() method would catch the broadcast from the PendingIntent, and I would perhaps start off a service from here to perform the background job.
If I'm on the right track so far, I have one challenge, which is that onUpdate() is not trig开发者_StackOverflowgered on adding the app widget to the desktop, and thus the widget button is not getting set up properly (it ends up doind nothing). Do I have to set the widget up with a configurationactivity, which in turn triggers AppWidgetProvider.onUpdate(), or is there a simpler solution to this?
If I'm not on the right track at all, any pointers to a better way of achieving what I'm trying to achieve would be very much appreciated. :)
Update:
Thought I might post some of the code here as well. Here is the receiver definition from the manifest:
<receiver android:name=".widget.QuickAddWidgetProvider" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/quickadd_widget_info" />
</receiver>
This is my resource file, defining the widget:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="72dp"
android:minHeight="72dp"
android:initialLayout="@layout/quickadd_widget"
android:updatePeriodMillis="0">
</appwidget-provider>
This is QuickAddWidgetProvider:
public class QuickAddWidgetProvider extends AppWidgetProvider {
@Override
public void onReceive(Context context, Intent intent) {
Log.v("QuickAdd", "onReceive()");
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.v("QuickAdd", "onUpdate()");
}
}
If I'm on the right track so far
Yes!
I have one challenge, which is that onUpdate() is not triggered on adding the app widget to the desktop, and thus the widget button is not getting set up properly (it ends up doind nothing)
Well, it should. Make sure your AppWidgetProvider
's entry in the manifest has the right <intent-filter>
to receive updates:
<receiver android:name=".AppWidget" android:label="@string/app_name" android:icon="@drawable/icon">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_provider"/>
</receiver>
精彩评论