Shan
Shan

Reputation: 1103

Unable to receive updated value from sharedPreference in Android Service

Iam stuck with this problem for more than 4 hours, iam unable to pass an updated value from a sharedPrefernce in Service class.

public class Background extends Service {
.....
.....
public int onStartCommand(Intent intent, int flags, int startId) 
{
    return Service.START_STICKY;
}
....
....
private void callService() {
    String prefCount=getSharedData("list_update_count");
    myb = new myBroad();
    Context context = this.getApplicationContext();
    myb.SetAlarm(context,prefCount);
}
....
....
public class myListener extends PhoneStateListener
{
    @Override
    public void onCallStateChanged(int state, String incomingNumber) 
    {
        super.onCallStateChanged(state, incomingNumber);
        if (state == TelephonyManager.CALL_STATE_IDLE)
        {
            String phoneNumber =   incomingNumber;
            callService();
        }
    }  

}

My BroadcastReceiver ------------------------------------------

    public class myBroad extends BroadcastReceiver{
    .....
    .....
    .....
    public void onReceive(Context context, Intent intent) {
    ....
    .....
    }
    public void SetAlarm(Context context,String prefCount){
        //here the prefCount is not receiving the updated value!!
    buildToast(prefCount,context);
    }
.....
}

When i launch the application after a force stop, The updated value from the sharedPreference is obtained correctly. Thanks ...

Upvotes: 1

Views: 488

Answers (2)

user3381480
user3381480

Reputation: 61

Have you try this?

SharedPreferences preferences = getSharedPreferences("preferences", Context.MODE_MULTI_PROCESS);

Sorry, Global is my own class that contains constants used on my projects, replace Global.PREFERENCES to your own SharedPreferences name.

Upvotes: 1

Bharat
Bharat

Reputation: 904

SharedPreferences pref = getSharedPreferences("MyPreference", 0);
     String prefCount = pref.getString("list_update_count", 0)

or in case you are using default sharedPreferences

 SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
 String prefCount = pref.getString("list_update_count", 0); 

Upvotes: 1

Related Questions