遵循示例here http://developer.android.com/guide/topics/appwidgets/index.html我轻松创建了我的小部件。
然后我向我的小部件添加了一个按钮,该按钮应该启动一个服务,因此我将以下代码添加到我的 WidgetProvider
@Override
public void onEnabled(Context context) {
Log.e("ERROR", "REMOVE ME"); // TODO remove. This is for eclipse logcat recognition
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
Intent intent = new Intent(context, RepairService.class);
PendingIntent pi = PendingIntent.getService(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.widget_boost, pi);
}
该代码肯定会被调用,但服务不会启动。我确信我可能错过了服务 PendingIntent 的实现,但我看不到什么。还有人知道吗?
好吧,我已经解决了它
public class WidgetProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Log.e("ERROR", "onUpdate method called");
final int N = appWidgetIds.length;
// Perform this loop procedure for each App Widget that belongs to this provider
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
// Create an Intent to launch ExampleActivity
Intent intent = new Intent(context, UpdateService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
Log("Pending Intent = " + pendingIntent.toString());
// Get the layout for the App Widget and attach an on-click listener to the button
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
views.setOnClickPendingIntent(R.id.widge, pendingIntent);
// Tell the AppWidgetManager to perform an update on the current App Widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
public static class UpdateService extends Service {
@Override
public void onCreate() {
.........
.........
}
// Service stuff here
}
}
我不完全确定在 onEnable 中这样做有什么问题。也许有人可以解释为什么。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)