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 都是空的。
然后我通过调试器运行它:
我在小部件类的 onReceive 中读取onUpdate() 初始化变量为空,并确保这些状态变量是静态的,但它们仍然为空。这是为什么,我如何在 onReceive 中保留这些值?
您的进程可能会在两次调用之间终止onReceive()。如果您希望保留来自 的数据BroadcastReceiver,例如AppWidgetProvider,请使用一些持久数据存储(数据库SharedPreferences、 或其他类型的文件)。静态数据成员只是一个缓存,仅此而已。
| 归档时间: |
|
| 查看次数: |
480 次 |
| 最近记录: |