我正在尝试制作一个主屏幕小部件,它将打开和关闭 gps(设置中的位置)。我仍然不明白如何处理按钮单击事件。
我从在线教程中获取了此代码。
public class LocationWidget extends AppWidgetProvider {
private static String SYNC_CLICKED = "automaticWidgetSyncButtonClick";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int count = appWidgetIds.length;
String status;
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
for (int i = 0; i < count; i++) {
int widgetId = appWidgetIds[i];
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
status = "OFF";
} else {
status = "ON";
}
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.activity_main);
remoteViews.setTextViewText(R.id.textView, status);
Intent intent = new Intent(context, LocationWidget.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.actionButton, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.activity_main);
remoteViews.setTextViewText(R.id.textView, "Button clicked");
Log.v("ACTION", intent.getAction());
}
}
在 onReceive 中,Log.v 返回“ACTION:android.appwidget.action.APPWIDGET_UPDATE”。所以我需要帮助以使按钮在单击时按我想要的方式运行。有人可以解释如何以及为什么?