2011-12-28 83 views
4

我有一个在android下运行的小部件,我希望它在用户单击小部件上的按钮时自行更新。Android AppWidgetProvider onReceive未调用按钮单击

出于某种原因,在我安装小部件后单击按钮时,从不会调用onReceive方法。

我有一个这样的的onUpdate方法在我的AppWidgetProvider类:

@Override 
public void onUpdate(Context context, AppWidgetManager appWidgetManager, 
        int[] appWidgetIds) { 

     super.onUpdate(context, appWidgetManager, appWidgetIds); 

     for (int i = 0; i < appWidgetIds.length; ++i) { 

       final RemoteViews rv = 
new RemoteViews(context.getPackageName(), R.layout.appwidget_provider);  

       final Intent nextIntent = 
new Intent(context, TestAppWidgetProvider.class); 
       nextIntent.setAction(TestAppWidgetProvider.NEXT_ACTION); 
       nextIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]); 

       final PendingIntent refreshPendingIntent = 
PendingIntent.getBroadcast(context, 0, 
           nextIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
       rv.setOnClickPendingIntent(R.id.next, refreshPendingIntent); 

       appWidgetManager.updateAppWidget(appWidgetIds[i], rv); 
     } 
} 

然后我就收到我有一个看起来像的方法:

@Override 
public void onReceive(Context ctx, Intent intent) { 

    super.onReceive(ctx, intent); 

    final String action = intent.getAction(); 

    if (action.equals(PREV_ACTION)) { 

     Toast.makeText(ctx, "Previous clicked..", Toast.LENGTH_SHORT).show(); 
    } else if (action.equals(NEXT_ACTION)) { 

     Toast.makeText(ctx, "Next was clicked..", Toast.LENGTH_SHORT) 
       .show(); 
    } 
    else { 
     Toast.makeText(ctx, "Other action..", Toast.LENGTH_SHORT).show(); 
    }   
} 

我有这个在我的清单文件太:

<receiver android:name="com.test.android.widget.TestAppWidgetProvider" > 
     <intent-filter > 
      <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> 
     </intent-filter> 
     <intent-filter > 
      <action android:name="com.test.android.widget.PREV" /> 
     </intent-filter> 
     <intent-filter > 
      <action android:name="com.test.android.widget.NEXT" /> 
     </intent-filter> 
     <meta-data 
      android:name="android.appwidget.provider" 
      android:resource="@xml/appwidget_info" /> 
</receiver> 

当我安装了小部件并点击下一个按钮后,onReceive方法d从来不会因为某种原因而被召唤......

回答

4

修正了它,原来是微不足道的。

这是因为onReceive甚至没有在窗口小部件创建时被调用,所以事件监听器没有设置。

增加了onReceive中的一些代码(设置setOnClickPendingIntent等)到一个函数,该函数在widget配置活动准备好更新小部件时调用。

+3

你能分享你的解决方案吗? – 2015-02-01 10:05:41