其他分享
首页 > 其他分享> > android-onUpdate()引入的变量在小部件类的onReceive中为null

android-onUpdate()引入的变量在小部件类的onReceive中为null

作者:互联网

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

解决方法:

对于AppWidgetReceiver,将首先调用onReceive(),然后根据收到的Action调用onUpdate(…)方法.所以在这里您要在onUpdate()中初始化状态,该状态将在onReceive()之后调用,因此在onReceive()中状态为null.

标签:android-appwidget,android,android-widget,onupdate
来源: https://codeday.me/bug/20191009/1877636.html