0

我已经实现了一个 App Widget 以在单击时启动我的活动。

onUpdate()方法WidgetProvider

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    super.onUpdate(context, appWidgetManager, appWidgetIds);

    final int N = appWidgetIds.length;
    for (int i=0; i<N; i++) {
        int appWidgetId = appWidgetIds[i];

        RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.mywidgetprovider_layout);
        // ....update updateViews here
        appWidgetManager.updateAppWidget(appWidgetId, updateViews);

        Intent onClickedIntent = new Intent(context,MyActivity.class);
        PendingIntent pi = PendingIntent.getActivity(context, 0, onClickedIntent, 0);
        updateViews.setOnClickPendingIntent(R.id.myView, pi);

        appWidgetManager.updateAppWidget(appWidgetId, updateViews);

     }
}

在主屏幕上添加小部件后,它按预期工作。

但有时之后,它无法再次启动活动!我必须删除小部件并再次添加。

我该如何解决?请帮忙。

4

2 回答 2

0

I know this is like two years late but I struggled with this too until today when I think I know what I was doing wrong. I think the main key is to focus on the use of the RemoteViews class. You prepare these objects as a sort of instruction set for a another process to follow. Setting the "on click pending intent" must done before sending it to the updateAppWidget method, so your first call to that method won't prime your "myView" object for clicks. Your code next sets the onClick trigger and calls updateAppWidget a second time. It looks like that one should work but there is a whole confusing subject regarding just when two intents are distinct or ambiguous which you may want to read about to understand why your code is working unpredictably. If I'm right, the take-away is to simply not call updateAppWidget the first time and then always make sure to set your onClick trigger whenever creating RemoteViews objects. I hope so anyway.

于 2013-01-14T06:09:23.653 回答
0

我会这样做:

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.mywidgetprovider_layout);    
    Intent onClickedIntent = new Intent(context,MyActivity.class);
    PendingIntent pi = PendingIntent.getActivity(context, 0, onClickedIntent, 0);
    updateViews.setOnClickPendingIntent(R.id.myView, pi);

    for (int i=0; i<appWidgetIds.length; i++) {
        appWidgetManager.updateAppWidget(appWidgetIds[i], updateViews);
     }
}

我不确定的一件事是调用super.onUpdate(). 我自己的小部件代码没有它并且似乎工作正常......不确定是否需要它。

我不知道这个重构是否会解决你的问题!

于 2011-02-03T20:47:08.643 回答