无法从我的业务接入共享preferences [英] Can't access SharedPreferences from my Service

查看:214
本文介绍了无法从我的业务接入共享preferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做

您好,大家好。

我有一个服务当中,设定每当服务启动或停止是一个布尔值,真或假(开始=真/停止= FALSE)。现在,当我尝试在我的活动,以获得布尔在那里,它永诺不到风度找到它。我怎样才能解决这个问题......这里的code为你们。

I got a Service which, set's a boolean to true or to false whenever the service is started or stopped (started = true / stopped = false) in the SharedPreference. Now when I try to get the Boolean out there in my Activity, it allways dosn't find it. How can I solve this... Here's the Code for you Guys.

code

在了Methode我的服务:

Methode in my Service:

private void setStarted(boolean started) {
    // SharedPreferences casten

    mPrefs = this.getSharedPreferences(LOG_TAG, MODE_PRIVATE);
    // Boolean in SharedPreferences hinzufügen
    SharedPreferences.Editor editor = mPrefs.edit();
    editor.clear().apply();
    editor.putBoolean(PREF_STARTED, started).commit();
    editor.commit();

    //mPrefs.edit().putBoolean(PREF_STARTED, started).commit();

    Log.d(LOG_TAG, "Variabel " + mPrefs.getBoolean(PREF_STARTED, false));
}

在我的活动

// mPrefs caten
        mPrefs = this.getSharedPreferences(GPSService.LOG_TAG, MODE_PRIVATE);

        // boolean holen ob service gestartet oder nicht
        run = mPrefs.getBoolean(GPSService.PREF_STARTED, false);

我如何获得布尔离开那里?它返回永诺我的默认值我曾在getBoolean了Methode放弃。

How do I get the boolean out of there? It allways returns me the default value I had to give in the getBoolean Methode.

感谢您的帮助提前

Safari浏览器

推荐答案

下面就是我成功地用我的应用程序之一某些code。它在应用中的各个部分使用,例如无论是从活动和服务:

Here is some code that I'm successfully using in one of my apps. It is used in various parts of the app, e.g. both from activities and services:

void putValue(Context context, String pref, boolean value) {
    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.putBoolean(pref, value);
    editor.commit();                
}

boolean getValue(Context context, String value, boolean defaultValue) {
    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
    return settings.getBoolean(value, defaultValue);
}

这篇关于无法从我的业务接入共享preferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆