我目前正在使用三个ImageButtons
创建我的第一个小部件。
我已经非常仔细地按照Clickable widgets in android描述的答案,但是我没有让它发挥作用。
我已经定义了三个字符串,这是我的行为:
private String playAction = "playService";
private String stopAction = "stopService";
private String resetAction = "resetService";
接下来在我的OnUpdate()
函数中,我添加了setOnclickPendingIntent
:
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
remoteViews.setOnClickPendingIntent(R.id.widget_play, getPendingSelfIntent(context, playAction));
remoteViews.setOnClickPendingIntent(R.id.widget_pause, getPendingSelfIntent(context, stopAction));
remoteViews.setOnClickPendingIntent(R.id.widget_reset, getPendingSelfIntent(context, resetAction));
manager = appWidgetManager;
// Build the intent to call the service
Intent intent = new Intent(context.getApplicationContext(), UpdateWidgetService.class);
// Update the widgets via the service
context.startService(intent);
}
getPendingSelfIntent
函数定义如下:
protected PendingIntent getPendingSelfIntent(Context context, String action) {
Intent intent = new Intent(context, MyWidgetProvider.class);
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
但是,onReceive
函数不会收到上述定义的操作。我当前记录了传入意图的所有操作,但唯一传递的是android.appwidget.action.APPWIDGET_UPDATE
操作。
为了完成,这就是我在Manifest中定义动作的方式:
<receiver
android:name="MyWidgetProvider"
android:icon="@drawable/ic_launcher"
android:label="My Widget">
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_info" />
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="playService" />
<action android:name="stopService" />
<action android:name="resetService" />
</intent-filter>
</receiver>
我已在Android文档中读到,无法使用ListView
函数设置属于集合(setOnClickPendingIntent
等)的元素。我的布局中有三个按钮。为了确保这不会导致错误,这就是XML的样子:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageButton
android:id="@+id/widget_play"
android:layout_width="50dp"
android:layout_height="50dp"
android:scaleType="fitCenter"
android:adjustViewBounds="true"
android:layout_marginRight="5dp"
android:src="@drawable/run"/>
<ImageButton
android:id="@+id/widget_pause"
android:layout_width="50dp"
android:layout_height="50dp"
android:scaleType="fitCenter"
android:adjustViewBounds="true"
android:layout_marginRight="5dp"
android:src="@drawable/pause"/>
<ImageButton
android:id="@+id/widget_reset"
android:layout_width="50dp"
android:layout_height="50dp"
android:scaleType="fitCenter"
android:adjustViewBounds="true"
android:src="@drawable/reset"/>
</LinearLayout>
对此事的任何帮助表示赞赏,因为我完全没有想法。我已经搜索过类似的问题,但他们都描述了我已经尝试过的事情。
答案 0 :(得分:3)
我认为您在设置pendingintents之后缺少对窗口小部件的更新:
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
如果这没有用,你也应该发布你的UpdateWidgetService.class。
Btw UpdateWidgetService.class做了什么?