onUpdate()intilized变量在widget类的onReceive中为null

时间:2013-12-18 06:36:05

标签: android android-widget android-appwidget onupdate

我在onUpdate()方法中初始化一个变量,然后调用onReceive()函数,该函数运行正常,但无法访问onUpdate()方法中的变量集。这是为什么?那些变量是字符串变量并被声明为public。我错过了什么吗?

public class WidgetTest extends AppWidgetProvider {
public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";
public String state;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) 
{
    Log.e("UPDATE", "Start");   
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
     state="State_update"

 System.out.println(state);// My variable is initilised
    Intent active = new Intent(context, WidgetTest.class);
    active.setAction(ACTION_WIDGET_RECEIVER);       
    PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
    remoteViews.setOnClickPendingIntent(R.id.buttonclick, actionPendingIntent);

    super.onUpdate(context, appWidgetManager, appWidgetIds);
    appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
    Log.e("UPDATE", "End");
}

@Override
public void onReceive(Context context, Intent intent) 
{
   super.onReceive(context, intent);
    Log.e("RECEIVE", "Start 2");
    if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) 
    {

            Log.e("Test", "My State is  "state);//it gives me null point exception;

    }
   Log.e("RECEIVE", "End");


}

onReceive中的状态变量给出了零点异常

1 个答案:

答案 0 :(得分:2)

对于AppWidgetReceiver,将调用第一个onReceive(),然后根据收到的操作,它将调用onUpdate(...)方法。所以你在onUpdate()中初始化状态,它将在onReceive()之后调用,因此onReceive()中的状态为 null