无法从Android服务中的sharedPreference接收更新的值

时间:2014-03-05 07:01:01

标签: android service sharedpreferences

Iam坚持这个问题超过4个小时,我无法从Service类的sharedPrefernce传递更新的值。

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();
        }
    }  

}

我的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);
    }
.....
}

当我在强制停止后启动应用程序时,可以正确获取sharedPreference中的更新值。 谢谢......

2 个答案:

答案 0 :(得分:1)

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

或者如果您使用默认的sharedPreferences

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

答案 1 :(得分:1)

你试试这个吗?

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

抱歉,Global是我自己的类,包含我的项目中使用的常量,将Global.PREFERENCES替换为您自己的SharedPreferences名称。