1

我正在编写一些代码,当屏幕打开时打开或关闭飞行模式(取决于用户的选择)。我保留了用户选择的标志(0 表示关闭,1 表示开启)。但出于某种原因,无论用户选择什么,在活动中选择 (airplanei) 的值始终为 1。我确定错误出现在我发布的代码中;最有可能不正确地使用 SharedPreferences。

活动代码:-

protected void airplane(int i) {
    // Store flag in SharedPreferences
    SharedPreferences flags = this.getSharedPreferences("toggleflags",
                    MODE_WORLD_READABLE);
    SharedPreferences.Editor editor = flags.edit();
    if (i == 0)
        editor.putInt("airplanei", 0);
    else if (i == 1)
        flags.edit().putInt("airplanei", 1);
    else if (i == -1)
        flags.edit().putInt("airplanei", -1);
    editor.commit();
}

广播接收器中的代码:-

public class Screen_On extends BroadcastReceiver{
@Override
public void onReceive(final Context context, Intent intent) {
    SharedPreferences flag = context.getSharedPreferences("toggleflags", 0);
    int i = flag.getInt("airplanei", 1);
    if (i == 0) {
            //Code to turn airplane mode off
    } else if (i == 1) {
            //Code to turn airplane mode on
    }
    }
}

谢谢你的时间。

4

2 回答 2

1

当 (i == 0) 使用 editor.putInt() 时,对于 (i == 1) 和 (i == -1) 使用 flags.edit()。

我相信你应该为他们使用 editor.putInt() 。

于 2012-05-29T20:42:35.087 回答
1

正如@Matt 已经说过的那样,您实际上创建了两个新实例,Editor但仅首先提交:

flags.edit().putInt("airplanei", 1); // New editor here
...
flags.edit().putInt("airplanei", -1);
...
editor.commit(); // Commit first editor instance
于 2012-05-29T20:47:42.793 回答