0
我有我在onUpdate中分配的變量,並且需要訪問我的應用小部件提供程序類的onReceive中的值。爲什麼我的AppWidgetProvider的onReceive中的這些狀態變量爲空?
public class MyWidgetProvider extends AppWidgetProvider {
private static String name;
private static SharedPreferences myPrefs;
private static final String START_ACTION = "start";
@Override
public void onUpdate(final Context context, final AppWidgetManager appWidgetManager,
final int[] appWidgetIds) {
views = new RemoteViews(context.getPackageName(), R.layout.layout_widget);
Intent intent1 = new Intent(context, MyAppWidgetProvider.class);
providerIntent.setAction(START_ACTION);
pendingIntent = PendingIntent.getBroadcast(context, 0, providerIntent, 0);
....
myPrefs = Context.getSharedPreferences("PrefsName", 0x0000);
name = "new name";
networkClient.requestItem(name, new JsonHandler {
@Override
public void requestSuccess(JSONObject resp) {
views.setOnClickPendingIntent(R.section, pendingIntent);
}
}
@Override
public void onReceive(@NonNull final Context context, @NonNull Intent intent) {
super.onReceive(context, intent);
if(intent.getAction().equals(START_ACTION)) {
myPrefs.edit().putString("someKey", name).commit();
}
}
我把日誌消息放在onReceive中,看到myPrefs和name都是null。
然後,我跑到它通過調試器:
- 的onUpdate被稱爲「myPrefs」被初始化的值,然後在「名」了。
- 我點了一個部分,onReceive被調用,在那裏我發現myPrefs和名稱爲null!
我讀onUpdate() intilized variable are null in onReceive of widget class並確保這些狀態變量是靜態的,但它們仍然爲空。爲什麼會這樣,我如何在onReceive中保留這些值?