[英]onUpdate() intilized variable are null in onReceive of widget class
我在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 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.