【问题标题】:onUpdate() intilized variable are null in onReceive of widget classonUpdate() intilized 变量在小部件类的 onReceive 中为空
【发布时间】:2013-12-18 06:36:04
【问题描述】:

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

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 中的状态变量给出空点异常

【问题讨论】:

    标签: android android-widget android-appwidget onupdate


    【解决方案1】:

    对于AppWidgetReceiver,首先会调用onReceive(),然后根据收到的Action调用onUpdate(...)方法。所以这里你在 onUpdate() 中初始化 state,它会在 onReceive() 之后被调用,因此 onReceive() 中的 state 是 null

    【讨论】:

    • 但是如果我再次删除并取回小部件,则首先调用 onUpdate 而不是 onreceive 并且我的变量被初始化然后我在 onReceive 中也得到空点
    • 我在 onUpdate 的 println 中得到了变量值
    • 每次系统都会创建一个新的 BroadcastReceiver 实例并调用 onReceive() 方法。在这里,您的状态变量是实例变量,每次创建对象时都将为空。为了克服这个问题,您可以将状态变量声明为静态
    • 这就是我想要的
    • @ShakeebAyaz 还有更多答案???你需要进一步解释吗?如果可以,有什么可以帮助您的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2021-07-07
    • 1970-01-01
    • 2013-04-05
    相关资源
    最近更新 更多