I have my own singleton class which inherits from Application. In all my activities I get this shared class by using DataClass dc = (DataClass) context.getApplicationContext();.
this seems to work but when I trie to acces the singleton in a custom BroadCastReceiver I have an other instance of the Application.
Is that possible? Does anyone have a solution for this?
This is expected behaviour.
If i am not mistaken, a BroadcastReceiver runs on a different process then your activity. That means you'll have a different instance of Application on your BroadcastReceiver.
Related
I have:
a MainActivity
a OtherActivity
a DatabaseService, which is instantiated in MainActivity and which holds Sqliteconnection and functions like List<data> getData()
How do I pass the DatabaseService to my OtherActivity ?
So far my DatabaseService was a Singleton and I referenced that Singleton from the OtherActivity, but I dont like that Solution.
I can't also pass it with putExtra, because the Object is too complex to serialize.
There should be a more easier way to inject or pass the Service to the activity.
Does anyone have any hint for me ?
What you need to do is binding your activities to the service (in your case: DatabaseService). Highly recommend you follow [this dev guide] https://developer.android.com/guide/components/bound-services and choose the simplest way to create a bound service: extending the binder class. So for short, what you need to do:
implement your service following the sample LocalService
config in AndroidManifest.xml:
<service android:name=".YourNewService" android:enabled="true"/>
for activities needs to interact with the service, just implement them similar to BindingActivity of the guide. (No worries on service instantiation, singleton, etc.)
Please note that you always can create a base BindingActivity class that handles all binding cores and let other activities extend the base binding class.
Happy coding!
I am new to Android and here i am stuck at a point .
There is a class (say class_A) , MainActivity and a Service class(which extends IntentService)
I have an instance of Class_A in my MainActivity which gets updated with user's response . I want to use the same instance in my Service class , so that on the basis of updated instance of Class_A i can perform task present in my Service Class (the service runs indefinitely) .
Any kind of help is appreciated . Or if the above approach is wrong please do suggest other methods of doing it .
I think I understand what you're asking. What you're probably looking for is a Singleton (which some people consider evil) or shared preferences http://developer.android.com/reference/android/content/SharedPreferences.html
What exactly is the purpose of Application class.
what are the benefits of extending it to a custom subclass
Why use it ?
Can global variables be stored in any other class achieve same goal as Application ?
Nice question !
Your application is a context that is always running while your activities and services are running.
It is also the first context to be created and the last to be destroyed.
Thus, it surrounds the life cycle of your app.
You can use the application class as a way to share data or components (for dependency injection for instance). For instance if you want to share a singleton between activities, you can create the instance in the application class and provide a getter, then all other contexts can get the singleton via
((cast to your class)getApplicationContext()).getFoo();
There may be some use cases where you need to do stuff before even your first activity is launched, then do it in the onCreate method of the application class.
On the other hand, you should never relie on the onDestroy method of the Application class, as it is not always called. There is no contract for that on Android.
But this is rare and, usually, you don't need to override the application class though. Dependency injection can be achieved in other ways by RoboGuice or Dagger for instance.
Two things makes this Class very useful:
Application class is instantiated before any other Activity.
It holds the Application Context
Context brings a host of resources for us: we can figure out some device properties, load some resources, initiate a SQLite database etc, etc.
All of this happens before any Activity loads, and all of this is globally available to the Activities.
Simple example of what I mean:
public class App extends Application{
private static Resources sResources;
//--I want to load strings resources from anywhere--
public static String loadStringResource(int resID) {
return sResources.getString(resID);
}
#Override
public void onCreate() {
super.onCreate();
sResources = getResources();
//---I want to load all preferences when my app starts---
PreferenceManager.setDefaultValues(this,R.xml.prefs,false);
}
}
Extending the Application class allows you to integrate into the application's lifecycle.
This is also useful to store global application-level information (though it's usually good to keep your activities 'independent')
The Application class is aware of the Application Context and is loaded when your app is loaded so it holds the proper callbacks for the application lifecycle before your activity starts. You most likely would not want to extend this class.
From the API docs:
There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.
http://developer.android.com/reference/android/app/Application.html
So I'm trying to make an application using the Singleton Method. I want to have a class that stores all the information about my device's bluetooth state/connections/devices, and I want to make multiple activites that can access these methods.
I know that I need to have a class that extends Application, then I can access everything by calling getApplication(). What I do not understand, is where I initialize this object. From my frame of reference, I have all of these separate Activities, and if I initialize the object in one, I'm going to need to use intents to pass the object to the next activity, which completely defeats the purpose of using the singleton method.
Any help would be appreciated, thanks.
Simply extend from android.app.Application. Then register it as the application class in your AndroidManifest.xml:
<application android:name="mypackage.MyApplication" ...>
In your class you will receive usual Android calls, such as in
#Override
public void onCreate() { }
where you will able to initialize your global instances.
In the activities fetch the instance of MyApplication downcasting with:
MyApplication app = (MyApplication) getApplication();
Hope that helps.
If you extended Application your class will be created as your app launches. It can be retrieved in Activity classes using getApplication()
Check here : http://www.kodejava.org/examples/12.html
and here : http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/
and here : http://inchoo.net/mobile-development/android-development/android-global-variables/
I want to access a "global" variable in my MyApp(extends Application) from a broadcastreceiver (registered in the manifest) and e.g. multiple activities. Now I seem to have different instances of my MyApp: one for the BCR and one for the activities. Could sb help me with my problem?
thanks alot
Joerg
What I get from this is that you are trying to create a method to having a single Context object. First off, to do this you would need a Singleton Pattern of MyApp to create your "global" variable. However I would advice against this for these reasons:
Different application components by default have different contexts (base, application).
A BroadcastReceiver defined in the manifest is invoked by the OS, not by your application.
Using a Singleton Pattern for a context object will lead to some very nasty dependencies.
You are going against the design and beauty of the Android Framework.
I would suspect the reason you are doing this is so your MyApp class can start different activities. This makes sense, but... you can get a Context Object from almost anywhere. Many things in Android extend the ContextWrapper class (think Java Objects with the Object class). So there is really no reason to ever have a "global" instance of this. In fact your BroadcastReceiver's onReceive() method accepts a context parameter. You can use this to start activities and what not.
If this is not why you are wanting the MyApp singleton class - and there are justifiable reasons for needing it, I would look at the implementation designed by Bill Pugh as it is the safest in Java taking into account thread synchronization and locking.
Hope this helps. Remember, don't fight the SDK, let it work for you!
I had a similar problem, I was able to access an object in the activity using this pattern:
public class MyReceiver extends android.content.BroadcastReceiver {
private Object _object;
public MyReceiver(Someobject) {
_object = the object;
}
#Override
public void onReceive(Context context, Intent intent) {
Do something to the object.
}
}
Then call MyReceiver(theobject) instead of new BroadcastReceiver().