Chand
Chand

Reputation: 320

Services stops when i close the activity

My project one service and one activity in my activity i am having 2 spinners and 1 button

i am starting the service from my activity. in the service it checks the onItemSelected on both dropdown list and run the code.

it works fine till is activity is active. if it is killed the service stops.

service is checking again n again from dropdownlist which is not accessible after i kill activity.

how can save the selected item in services and use it .

in mainactivity

    dropdown = (Spinner) findViewById(R.id.spinner1);
    dropdown.setOnItemSelectedListener(new CustomOnItemSelectedListener());
    dropdown2 = (Spinner) findViewById(R.id.Spinner01);
    dropdown2.setOnItemSelectedListener(new CustomOnItemSelectedListener());

i have used below code in services..

    public void onStart(Intent intent, int startId) {

     String m1 = (String) MainActivity.dropdown.getSelectedItem();
      String m1 = (String) MainActivity.dropdown2.getSelectedItem();

    if (m1 = "xyz") 
    {
   switch m2:           
        //code
    }
    else {
        switch m2:
          //code
         }

Upvotes: 0

Views: 53

Answers (1)

Nadir Belhaj
Nadir Belhaj

Reputation: 12073

you can save your value in SharedPrefs

PreferenceManager.getDefaultSharedPreferences(this).edit().putString("value","myvalue").apply();

and get it next time this way

String v = PreferenceManager.getDefaultSharedPreferences(this).getString("value","");

Upvotes: 1

Related Questions