Hussein
Hussein

Reputation: 681

Can I use shared preference in an android service?

I have an android application that contains some android background service which work after device boots up without running the app and the service sends notifications to the user. I need some details about the last login to the application (the last entered user name and password) to engage with the service code .

By the way, I am using shared preference in the login page to store user name and password for the last person logged in, so can I use these shared preferences to get the username and password from them in the service while the app is not running?

I have tried to do it and this is my code from the android service ...

    saveLog = loginPref.getBoolean("saveLog", false);
    String userName = "";
    String passWord = "";

    if (saveLog == true) {
        userName =loginPref.getString("username", "");
        passWord =loginPref.getString("password", "");
    }

Here is the login activity code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    log = (Button) findViewById(R.id.butLogin);
    log.setOnClickListener(this);
    loginPref = getSharedPreferences("loginPref", MODE_PRIVATE);
    loginPrefEditor = loginPref.edit();
    editUsername = (EditText) findViewById(R.id.userEB);
    editPassword = (EditText) findViewById(R.id.passEB);
    saveCheckBox = (CheckBox) findViewById(R.id.saveCB);

    saveLog = loginPref.getBoolean("saveLog", false);

    if (saveLog == true) {
        editUsername.setText(loginPref.getString("username", ""));
        editPassword.setText(loginPref.getString("password", ""));
        saveCheckBox.setChecked(true);
    }
}

Here, I store the value of these shared preferences from the Login Activity

        if (saveCheckBox.isChecked()) {
            loginPrefEditor.putBoolean("saveLog", true);
            loginPrefEditor.putString("username", username);
            loginPrefEditor.putString("password", password);
            loginPrefEditor.commit();
        } else {
            loginPrefEditor.clear();
            loginPrefEditor.commit();
        } 

Upvotes: 2

Views: 2636

Answers (1)

Yasin Kaçmaz
Yasin Kaçmaz

Reputation: 6663

Of course you can do , my working code here :

mLoginPreferences=getSharedPreferences(getResources().getString(R.string.pref_name), Context.MODE_PRIVATE);

You can put variables to prefs , clear prefs etc.. whatever you want.

Don't forget this : services is like activites but they running on background.

Upvotes: 1

Related Questions