android - 在广播接收器中使用共享首选项

标签 android android-activity broadcastreceiver sharedpreferences

我开发了一个具有一个 Activity 和一个广播接收器的应用程序。我想以一种可以使用在 Activity 中设置的某些设置的方式设置 braodcast 接收器。

我使用下面的代码及其在两个 Activity 之间的工作,但在 Activity 和广播接收器之间无法捕获设置。

这里是我保存 avtivity 的代码:

private void savePreferences(String key, String value) {
    SharedPreferences sp = PreferenceManager
            .getDefaultSharedPreferences(this);
    Editor edit = sp.edit();
    edit.putString(key, value);
    edit.commit();
}

braodcast 接收器中的这段代码:

 @Override
    public void onReceive(Context context, Intent intent) {

     Bundle extras = intent.getExtras();




        SharedPreferences sp = context.getSharedPreferences("myPrefs", 
                Context.MODE_PRIVATE);
        String Password = sp.getString("PASSWORD", "1234");

         int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(context, 
                         "password is"+Password, duration);
            toast.show();
  }

最佳答案

您的接收器正在使用名为“myPrefs”的文件,但您在设置 Activity 中的首选项时使用的是默认文件名。

使用这个打开名为“myPrefs”的特定首选项文件

SharedPreferences sp = context.getSharedPreferences("myPrefs", 
            Context.MODE_PRIVATE);

或者打开默认文件的这个

SharedPreferences sp = PreferenceManager
        .getDefaultSharedPreferences(this);

但不是两者的混合,因为它们指的是不同的首选项文件。

关于android - 在广播接收器中使用共享首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19338166/

相关文章:

android - 如何在切换 Activity 之间停止动画?

android - 在选项卡之间共享一个对象(不同的 Activity )

android - Activity 中的静态内容

java - 手动终止应用程序时如何获取广播接收器?

android - Flutter:如何保持应用程序在后台运行

java - 仅当 RecyclerView 可滚动时,如何向 RecyclerView 中的最后一个 View 添加填充?

Intent 返回 Activity 后,android alertdialog 不显示

android - 我如何判断(通过检查框架代码)Android Intent 广播是否为 'sticky"

android - 无法获得ACTION_PACKAGE_REMOVED广播-Android 10/设置

android - 从代码注册广播接收器以在远程进程中运行