Reputation: 143
I create a SharedPreferences called ALARM with a map called ("alarm",boolean), ("alarm",boolean)'s boolean value changed time to time in MainActivity, and received in a BroadcastReceiver.
The problem is: when I change the value in MainActivity time to time, BroadcastReceiver only change once. What's wrong with my code?
In below code, the start() align to a button, when clicked, change boolean to true. I can see a true value received in the BroadcastReceiver as well. But then I click the stop(), boolean change to false in MainActivity, but still see a true value received in BroadcastReceiver.
If I click stop() first, then I always see false value in BroadcastReceiver.(even I click start() many time)
Thanks.
MainActivity:
public class MainActivity extends AppCompatActivity {
SharedPreferences ALARM;
SharedPreferences.Editor editorALARM;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ALARM = getSharedPreferences("ALARM", MODE_PRIVATE);
editorALARM = ALARM.edit();
}
// start data service
public void start(View view) {
editorALARM.putBoolean("alarm", true).apply();
Log.e("start",""+ALARM.getBoolean("alarm", false));
Intent intent = new Intent();
intent.setAction("xxx.ALARM");
sendBroadcast(intent);
}
// stop data service
public void stop(View view) {
editorALARM.putBoolean("alarm", false).apply();
Log.e("stop",""+ALARM.getBoolean("alarm", true));
Intent intent = new Intent();
intent.setAction("xxx.ALARM");
sendBroadcast(intent);
}
}
BroadcastReceiver:
public class Receiver extends BroadcastReceiver {
SharedPreferences ALARM;
@Override
public void onReceive(Context context, Intent intent) {
ALARM = context.getSharedPreferences("ALARM", Activity.MODE_PRIVATE);
Log.e("actual",""+ALARM.getBoolean("alarm", false));
}
}
Upvotes: 1
Views: 580
Reputation: 143
It is due to the android: process =":remote" in manifests.xml, after remove it. I got correct boolean.
Upvotes: 3
Reputation: 1405
replace-
editorALARM.putBoolean("alarm", true).apply();
with-
editorALARM.putBoolean("alarm", true).commit();
will work for you
Upvotes: 0