我在android中有这个小部件,它显示一个图像并由广播接收器定期更新。现在,我希望通过单击窗口小部件,让用户能够启动配置屏幕(首选项活动)。在这里:
小部件提供程序类:
public class MyProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
ComponentName thisWidget = new ComponentName(context.getApplicationContext(), MyProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
RemoteViews rViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
for (int widgetId : appWidgetIds) {
// setting onClickListener - at least i TRY to
Intent onClickIntent = new Intent(context, Preferences.class);
PendingIntent onClickPendingIntent = PendingIntent.getBroadcast(context, 0, onClickIntent, 0);
rViews.setOnClickPendingIntent(R.id.graph, onClickPendingIntent);
appWidgetManager.updateAppWidget(widgetId, rViews);
}
}
}
小部件的更新从此处触发:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context.getApplicationContext());
int[] allWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
ComponentName myWidget = new ComponentName(context.getApplicationContext(), MyProvider.class);
int[] allMyWidgetIds = appWidgetManager.getAppWidgetIds(myWidget);
for (int widgetId : allMyWidgetIds)
{
RemoteViews rViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
// update the widgets content, i.e. picture
appWidgetManager.updateAppWidget(widgetId, rViews);
}
// schedule next update
Calendar c = Calendar.getInstance();
c.add(Calendar.SECOND, Config.UPDATE_RATE);
Date d = new Date(c.getTimeInMillis());
Intent timerIntent = new Intent(context.getApplicationContext(), TimeIntervalReceiver.class);
timerIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
PendingIntent timerPendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, timerIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager aManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
aManager.set(AlarmManager.RTC, d.getTime(), timerPendingIntent);
}
}
提一下:Preference.java-Activity在Manifest中注册,可以正确启动(我通过将其设置为启动活动来验证)。 无论如何,onclick功能根本不起作用:( 我还尝试将代码移动到更新小部件的“MyReceiver”类:没有:(
我已经看过了: * Android: Clickable imageview widget * http://www.vogella.de/articles/AndroidWidgets/article.html
然而,这根本没有帮助:(
这里有谁能告诉我问题出在哪里?
答案 0 :(得分:3)
尝试更改此行:
PendingIntent onClickPendingIntent = PendingIntent.getBroadcast(context, 0, onClickIntent, 0);
到
PendingIntent onClickPendingIntent = PendingIntent.getActivity(context, 0, onClickIntent, 0);
答案 1 :(得分:0)
PendingIntent onClickPendingIntent = PendingIntent.getActivity(context,0,onClickIntent,0);
检索将开始新活动的PendingIntent
请参阅链接以获取完整参考资料