为什么我的 AppWidgetProvider 的 onReceive 中的这些状态变量为 null?

Mar*_*usH 0 java android android-widget android-appwidget

我有分配给 onUpdate 的变量,需要访问我的应用程序小部件提供程序类的 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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

我把日志消息放在 onReceive 中,看到 myPrefs 和 name 都是空的。

然后我通过调试器运行它:

  1. onUpdate 被调用,“myPrefs”被初始化一个值,然后“name”也被初始化。
  2. 我单击了一个部分并调用了 onReceive,在那里我发现 myPrefs 和 name 为空!

在小部件类的 onReceive 中读取onUpdate() 初始化变量为空,并确保这些状态变量是静态的,但它们仍然为空。这是为什么,我如何在 onReceive 中保留这些值?

Com*_*are 5

您的进程可能会在两次调用之间终止onReceive()。如果您希望保留来自 的数据BroadcastReceiver,例如AppWidgetProvider,请使用一些持久数据存储(数据库SharedPreferences、 或其他类型的文件)。静态数据成员只是一个缓存,仅此而已