Pionas
Pionas

Reputation: 346

Android how get Context from specific class being in Service

I created Service class. I can run it anywhere where I want, but I always need Context from MainMenuActivity.class. I tried use getApplicationContext and getBaseContext but they show another class.

Thanks for answer

public class MainActivity extends ActionBarActivity {

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            startService(new Intent(this, MyService.class));
    }

}


public class MyService extends Service  {
    private Handler handler = new Handler();
    private MyLocationListener mylistener;
        public void onCreate() {
            handler.postDelayed(new runnable(), 10000);
    }

    private class runnable implements Runnable {
            @Override
            public void run() {
            mylistener = new MyLocationListener();
        }
    }
}

public class MyLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location loc) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
    }
}

[EDIT] When I used getApplicationContext() or getBaseContext or MainActivity.this to getDefaultSharedPreferences, always it will be the same?

Upvotes: 2

Views: 778

Answers (2)

Chintan Soni
Chintan Soni

Reputation: 25267

Solution: 1

In that case you have to use, defaultSharedPreferences. You can access the default shared preferences instance by:

PreferenceManager.getDefaultSharedPreferences(Context context):

Example:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

This preference is shared across all your Activity and Service classes.

Solution: 2

You can create sharedPreference instance in your application class like:

public class MyApplication extends Application { public static SharedPreferences preferences;

@Override
public void onCreate() {
    super.onCreate();

    preferences = getSharedPreferences("Preferences", MODE_PRIVATE);
}

}

And then you can manage your preferences as:

MyApplication.preferences.getString("key", "default");

Upvotes: 1

ShAkKiR
ShAkKiR

Reputation: 929

add context parameter to your service class methods

public void myMethodInsideServiceClass(Context context){
   //bluh bluh
}

so that you can call from Activity Class like this

myMethodInsideServiceClass(this);

you can also try

public class MyActivity extends Activity {
     public static myActivity;
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         myActivity=this;
     }
}

so that you can use myActivity across the application (i was not using editor to type code, sorry for syntax error)

Upvotes: 0

Related Questions