Get Context in a Service
Service is a Context
Android getContext on a background Service
Service extends Context. You can use this
, where this
is the reference to the Service
instance.
Putting more details on my comment below regarding the following code of SubscribeService class:
@Override
public void onCreate() {
super.onCreate();
context = this;
context = MyApp.getContext();
}
In your Service
's onCreate()
context = this
cannot be null
by a fundamental programming paradigm.
How can I get the application context from an Android Service?
ctx.getApplicationContext().startActivity(i)
boom.
Android how get Context from specific class being in Service
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");
Related Topics
Android App Crashes When Launched in Debug Mode
Dynamic Listview Adding "Load More Items" at the End of Scroll
Delete Alarm from Alarmmanager Using Cancel() - Android
Android Broadcast Receiver Bluetooth Events Catching
How to Share Same Data Between Multiple Activities
Recyclerview Inside Scrollview Not Scrolling Smoothly
Passing Argument to Dialogfragment
Encryption Error on Android 4.2
Detecting Sms Incoming and Outgoing
How to Restrict the Edittext to Accept Only Alphanumeric Characters
Find Out If Listview Is Scrolled to the Bottom
Get List of Photo Galleries on Android
How to Force the Action Bar to Be at the Bottom in Ics
How to Create a Custom Notification Layout in Android
First Launch Take Long Time (Classloader Referenced Unknown Path)
Changing Overflow Icon in the Action Bar