Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to get the updated value of a shred preference in a background service.
I am setting the shared preference in mainactivity and getting the value in bg service, but I am only able to retrieve the previous value and not the updated one.

What I have tried:

selected_dev = getSharedPreferences("battery_widget", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
<pre>SharedPreferences.Editor editor = selected_dev.edit();
		if(Integer.parseInt(min.getText().toString())!=0 && Integer.parseInt(max.getText().toString())!=0&& Integer.parseInt(max.getText().toString())>Integer.parseInt(min.getText().toString())) {
			editor.putInt("min", Integer.valueOf(min.getText().toString()));
			editor.putInt("max", Integer.valueOf(max.getText().toString()));
			min3 = Integer.valueOf(min.getText().toString());
			max3 = Integer.valueOf(max.getText().toString());
			min.setText("");
			max.setText("");
			min.setHint(String.valueOf(min3));
			max.setHint(String.valueOf(max3));
			editor.apply();
		}else{
			Toast.makeText(getApplicationContext(),"The values must be set in the following order min/max",Toast.LENGTH_LONG).show();
			min.setText("");
			max.setText("");
		}



//Service
selected_dev = getSharedPreferences("battery_widget", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);

if(selected_dev.getInt("min",0)!=0 && selected_dev.getInt("max",0)!=0) {
			BATTERY_LOWER_LEVEL = selected_dev.getInt("min", 0);
			BATTERY_UPPER_LEVEL = selected_dev.getInt("max", 0);
		}
Posted
Comments
David Crow 6-Apr-18 23:28pm    
At what point does getInt() get called?

Consider using SharedPreferences.OnSharedPreferenceChangeListener in your service so that the call to getInt() does not happen too early.
Member 10850253 7-Apr-18 8:39am    
That is not the problem, the problem I have is that the service runs in a different process.
<service android:name="com.hataflabs.batterywidget.ConnectService"
            android:enabled="true"
            android:process=":remote" >
            <intent-filter>
                <action android:name="com.hataflabs.batterywidget.ConnectService" />
            </intent-filter>

        </service>
David Crow 7-Apr-18 12:42pm    
"...the problem I have is that the service runs in a different process."

I fail to see the relevancy. Shared preferences work across process boundaries.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900