【问题标题】:Passing value from MainActivity to Broadcast Receiver using SharedPreference使用 SharedPreference 将值从 MainActivity 传递到广播接收器
【发布时间】:2017-05-30 11:28:02
【问题描述】:

我是 android 编程的新手,我正在尝试构建一个应用程序,它会在收到用户的消息时更改配置文件。该应用程序基本上有一个activity 和一个broadcast receiver。我提示用户设置密码以更改配置文件,密码保存在Shared Preference 中,我在MainActivity 中使用它。我无法在broadcast receiver 类中检索存储在shared preference 中的密码。此外,我只能使用Shared Preference 来存储密码。MainActivityBroadcast Receiver、布局和Android manifest 的代码文件如下。非常感谢您的帮助。

MainActivity.java

public class MainActivity extends AppCompatActivity {



public EditText setPass;
public Button submit;
public static String password;


SharedPreferences sharedPreferences;
boolean b=false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setPass=(EditText)findViewById(R.id.setPassEditId);
    submit=(Button)findViewById(R.id.submitButtonId);

    sharedPreferences= getApplicationContext().getSharedPreferences("Pritom",Context.MODE_PRIVATE);

    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            password=setPass.getText().toString();

            SharedPreferences.Editor editor=sharedPreferences.edit();
            editor.putString("password",password);
            editor.commit();
            Toast.makeText(getApplicationContext(),"Password saved successfully"+password,Toast.LENGTH_LONG).show();
            //b=sharedPreferences.contains("password")?true:false;
            //Toast.makeText(getApplicationContext(),"b:"+b,Toast.LENGTH_LONG).show();
        }
    });


}

}

这里,在MainActivity 类中,变量b 返回true,这意味着shared preference 存在。

MyReceiver.java

public class MyReceiver extends BroadcastReceiver {

public AudioManager audioManager;
public String me = "";
public String last = "";
public static final String SMS_BUNDLE = "pdus";
public SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs";
boolean b = false;



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

    sharedPreferences = context.getSharedPreferences("Pritom", context.MODE_PRIVATE);
    String pass3 = sharedPreferences.getString("password", null);
    audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "";
        if (bundle != null) {
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i = 0; i < msgs.length; i++) {
                msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                str += "SMS from " + msgs[i].getOriginatingAddress();
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "n";

                String smsBody = msgs[i].getMessageBody().toString();

                if (smsBody.equals("@general" + pass3)) {
                    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                    audioManager.setRingerMode(audioManager.RINGER_MODE_NORMAL);
                }
            }

            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }


    } 
}

这里的问题是pass3shared preference 中检索值没有返回任何用于检查消息的if 语句不起作用。

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver
        android:name=".MyReceiver">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>

        </intent-filter>
    </receiver>
</application>

请帮助我。谢谢。

【问题讨论】:

  • 我正在广播接收器的 Shared Preference 中检索密码,但我无法检索它 ....好吧,有点混乱……你能说清楚吗?
  • 我认为问题在于您的活动和广播接收器正在访问两个不同的共享首选项文件。尝试在广播接收器中使用context.getApplicationContext().getSharedPreferences(....)
  • @Opiatefuchs,我已经更新了我的问题。
  • @Titus,我必须在我的activityreceiver 中都使用context.getApplicationContext().getSharedPreferences() 吗?
  • 我认为如果你只将它添加到广播接收器中它会起作用。传递给onReceive(...) 的上下文因调用广播接收器的人员而异。

标签: java android broadcastreceiver android-sharedpreferences


【解决方案1】:
//Inside onReceive method
sharedPreferences = context.getSharedPreferences("Pritom", context.MODE_PRIVATE);

// Instead of this line, use
sharedPreferences= getApplicationContext().getSharedPreferences("Pritom", Context.MODE_PRIVATE);

【讨论】:

  • 此代码有效,可能您尚未将密码存储在共享首选项中。
  • 我已经将密码存储在shared preference,这就是我写代码的原因:editor.putString("password",password);editor.commit();
【解决方案2】:

您有可能在设置密码之前收到广播。 在收到短信时注册的广播接收器,这意味着它在收到短信时调用。

当收到短信但您仍然没有为共享偏好分配密码时怎么办?在这种情况下,您无法从首选项中获取密码。

请检查该场景并对其进行一些更改。

【讨论】:

  • 这种情况我该怎么办?
  • 这是第一次设置密码吧? @PritomMazumdar
  • 是的,这是第一次
  • 您可以尝试使用虚拟密码或将其视为 null 并执行您的操作
  • 我已经尝试了所有这些,虚拟密码和 null 但没有任何效果,我什至卸载了应用程序并重新安装了它但仍然没有运气:(
猜你喜欢
  • 1970-01-01
  • 2012-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多