Android singleton thread talking to server - android

This is mostly a design decision question.
I have an activity, a broadcast receiver, and a class that talks to my server (call it ServerAccess).
ServerAccess naturally needs to be in a thread of its own since it will be handling some network tasks. The activity needs to have its UI updated from the results of ServerAccess (so it needs some way to access the UI thread). The broadcast receiver also sends needs to send data to ServerAccess.
My question is, should I make ServerAccess a singleton thread? If so, how do you achieve that in Android? My reason for making it singleton is that every time any data exchange occurs from the server, I needs to query some basic user information from the server before I can start exchanging data. I would not like to query this basic user information every time the broadcast receiver receives a broadcast, or every time the activity is opened. Instead, I think a better idea would be to fetch the singleton ServerAccess if it is already created and start exchanging data. If ServerAccess was already instantiated then it would have already fetched that basic user information from the server.
Now would an AsyncTask be the way to go forward with this? Or to make a thread in my Application class like so? Or a singleton Service would be a better idea?

I do think you have to make it singleton. To make a singleton class create a static object of that class and then create a static method getInstance() and here if the object of the class is null then create the instance of the classs else return the instance ..
Example :
public class ServerAccess{
public static ServerAccess severAccess = null;
public static ServerAccess getInstance(){
if(serverAccess != null)return serverAccess;
serverAccess = new ServerAccess();
return serverAccess;
}
}

Related

Is it a good practice to save activity instance in a WeakReference

Here, in this answer Activity instance is saved in WeakReference<Activity> variable. So that it will avoid memory leaks. Is it a good practice to do so?
public class BackgroundService extends IntentService {
private static WeakReference<Activity> mActivityRef;
public static void updateActivity(Activity activity) {
mActivityRef = new WeakReference<>(activity);
}
}
I'm using mActivityRef.get() and casting it to required activity object. Using that object, accessing the methods in activity.
The purpose is to access Activity methods from service, this code does the work but as per the comments I'm confused whether to use it or not
I've referred the document yet not clear.
Is it a good practice to do so?
No.
The purpose is to access Activity methods from service
That activity may not exist. For example, the user could press BACK and destroy the activity while the service is running. Calling methods on a destroyed activity will likely lead to crashes.
Use an event bus (LocalBroadcastManager, greenrobot's EventBus, etc.) for loosely-coupled communications between components, such as between services and activities. Have the activity register for events when it is visible, and have the service post events as needed.
No its not a good practice to store a reference of Activity anywhere in your project but if you want do, create an interface implement your activity with interface and pass that interface as a communication way between your activity and IntentService to your service.
Now your service has a reference of your activity's (selected) methods. Access your data through that interface and clear reference after its usage.

Android, understanding AsyncTask

Are specific AsyncTask's for specific activities? Or could I have say a RESTful APIManager which called one of four AsyncTask Classes, APIGET APIPOST APIPUT APIDELETE and be able to handle the network code that way? My idea is to be able to call something like this throughout my UI code.
<edit> Class UserPrefs;
APIManager.createUser(JSONObject info);
APIManager.createUser {
// handle info
APIPost newPost = new APIPost(info);
}
APIPost extends AsyncTask {
doInBackground {
//network code
<edit> UserPrefs.save(result);
}
}
Would this model be possible? Or am I misusing AsyncTask?
AsyncTasks are a natural fit for a RESTful service, but they are not tied to the lifecycle of Activities. You may create and start an Async task, but by the time the task finishes its background work and calls onPostExecute, the originating activity no longer exists in memory. Because of this, you should have a better plan for how to store local data than to keep it in an Activity member, where it can and will disappear frequently. To avoid thrashing, you should save the data somewhere. Candidates for saving local data are SharedPreferences, the file system, a database or the Application singleton object depending on the nature of the data and your app.
You could use ExecutorService, AsyncTasks are using it internally. Very easy to use.

Why extend the Android Application class?

An extended Application class can declare global variables. Are there other reasons?
Introduction:
If we consider an apk file in our mobile, it is comprised of
multiple useful blocks such as, Activitys, Services and
others.
These components do not communicate with each other regularly and
not forget they have their own life cycle. which indicate that
they may be active at one time and inactive the other moment.
Requirements:
Sometimes we may require a scenario where we need to access a
variable and its states across the entire Application regardless of
the Activity the user is using,
An example is that a user might need to access a variable that holds his
personnel information (e.g. name) that has to be accessed across the
Application,
We can use SQLite but creating a Cursor and closing it again and
again is not good on performance,
We could use Intents to pass the data but it's clumsy and activity
itself may not exist at a certain scenario depending on the memory-availability.
Uses of Application Class:
Access to variables across the Application,
You can use the Application to start certain things like analytics
etc. since the application class is started before Activitys or
Servicess are being run,
There is an overridden method called onConfigurationChanged() that is
triggered when the application configuration is changed (horizontal
to vertical & vice-versa),
There is also an event called onLowMemory() that is triggered when
the Android device is low on memory.
Application class is the object that has the full lifecycle of your application. It is your highest layer as an application. example possible usages:
You can add what you need when the application is started by overriding onCreate in the Application class.
store global variables that jump from Activity to Activity. Like Asynctask.
etc
Sometimes you want to store data, like global variables which need to be accessed from multiple Activities - sometimes everywhere within the application. In this case, the Application object will help you.
For example, if you want to get the basic authentication data for each http request, you can implement the methods for authentication data in the application object.
After this,you can get the username and password in any of the activities like this:
MyApplication mApplication = (MyApplication)getApplicationContext();
String username = mApplication.getUsername();
String password = mApplication.getPassword();
And finally, do remember to use the Application object as a singleton object:
public class MyApplication extends Application {
private static MyApplication singleton;
public MyApplication getInstance(){
return singleton;
}
#Override
public void onCreate() {
super.onCreate();
singleton = this;
}
}
For more information, please Click Application Class
Offhand, I can't think of a real scenario in which extending Application is either preferable to another approach or necessary to accomplish something. If you have an expensive, frequently used object you can initialize it in an IntentService when you detect that the object isn't currently present. Application itself runs on the UI thread, while IntentService runs on its own thread.
I prefer to pass data from Activity to Activity with explicit Intents, or use SharedPreferences. There are also ways to pass data from a Fragment to its parent Activity using interfaces.
The Application class is a singleton that you can access from any activity or anywhere else you have a Context object.
You also get a little bit of lifecycle.
You could use the Application's onCreate method to instantiate expensive, but frequently used objects like an analytics helper. Then you can access and use those objects everywhere.
Best use of application class.
Example: Suppose you need to restart your alarm manager on boot completed.
public class BaseJuiceApplication extends Application implements BootListener {
public static BaseJuiceApplication instance = null;
public static Context getInstance() {
if (null == instance) {
instance = new BaseJuiceApplication();
}
return instance;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onBootCompleted(Context context, Intent intent) {
new PushService().scheduleService(getInstance());
//startToNotify(context);
}
Not an answer but an observation: keep in mind that the data in the extended application object should not be tied to an instance of an activity, as it is possible that you have two instances of the same activity running at the same time (one in the foreground and one not being visible).
For example, you start your activity normally through the launcher, then "minimize" it. You then start another app (ie Tasker) which starts another instance of your activitiy, for example in order to create a shortcut, because your app supports android.intent.action.CREATE_SHORTCUT. If the shortcut is then created and this shortcut-creating invocation of the activity modified the data the application object, then the activity running in the background will start to use this modified application object once it is brought back to the foreground.
I see that this question is missing an answer. I extend Application because I use Bill Pugh Singleton implementation (see reference) and some of my singletons need context. The Application class looks like this:
public class MyApplication extends Application {
private static final String TAG = MyApplication.class.getSimpleName();
private static MyApplication sInstance;
#Contract(pure = true)
#Nullable
public static Context getAppContext() {
return sInstance;
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate() called");
sInstance = this;
}
}
And the singletons look like this:
public class DataManager {
private static final String TAG = DataManager.class.getSimpleName();
#Contract(pure = true)
public static DataManager getInstance() {
return InstanceHolder.INSTANCE;
}
private DataManager() {
doStuffRequiringContext(MyApplication.getAppContext());
}
private static final class InstanceHolder {
#SuppressLint("StaticFieldLeak")
private static final DataManager INSTANCE = new DataManager();
}
}
This way I don't need to have a context every time I'm using a singleton and get lazy synchronized initialization with minimal amount of code.
Tip: updating Android Studio singleton template saves a lot of time.
I think you can use the Application class for many things, but they are all tied to your need to do some stuff BEFORE any of your Activities or Services are started.
For instance, in my application I use custom fonts. Instead of calling
Typeface.createFromAsset()
from every Activity to get references for my fonts from the Assets folder (this is bad because it will result in memory leak as you are keeping a reference to assets every time you call that method), I do this from the onCreate() method in my Application class:
private App appInstance;
Typeface quickSandRegular;
...
public void onCreate() {
super.onCreate();
appInstance = this;
quicksandRegular = Typeface.createFromAsset(getApplicationContext().getAssets(),
"fonts/Quicksand-Regular.otf");
...
}
Now, I also have a method defined like this:
public static App getAppInstance() {
return appInstance;
}
and this:
public Typeface getQuickSandRegular() {
return quicksandRegular;
}
So, from anywhere in my application, all I have to do is:
App.getAppInstance().getQuickSandRegular()
Another use for the Application class for me is to check if the device is connected to the Internet BEFORE activities and services that require a connection actually start and take necessary action.
Source: https://github.com/codepath/android_guides/wiki/Understanding-the-Android-Application-Class
In many apps, there's no need to work with an application class directly. However, there are a few acceptable uses of a custom application class:
Specialized tasks that need to run before the creation of your first activity
Global initialization that needs to be shared across all components (crash reporting, persistence)
Static methods for easy access to static immutable data such as a shared network client object
You should never store mutable instance data inside the Application object because if you assume that your data will stay there, your application will inevitably crash at some point with a NullPointerException. The application object is not guaranteed to stay in memory forever, it will get killed. Contrary to popular belief, the app won’t be restarted from scratch. Android will create a new Application object and start the activity where the user was before to give the illusion that the application was never killed in the first place.
To add onto the other answers that state that you might wish store variables in the application scope, for any long-running threads or other objects that need binding to your application where you are NOT using an activity (application is not an activity).. such as not being able to request a binded service.. then binding to the application instance is preferred. The only obvious warning with this approach is that the objects live for as long as the application is alive, so more implicit control over memory is required else you'll encounter memory-related problems like leaks.
Something else you may find useful is that in the order of operations, the application starts first before any activities. In this timeframe, you can prepare any necessary housekeeping that would occur before your first activity if you so desired.
2018-10-19 11:31:55.246 8643-8643/: application created
2018-10-19 11:31:55.630 8643-8643/: activity created
You can access variables to any class without creating objects, if its extended by Application. They can be called globally and their state is maintained till application is not killed.
The use of extending application just make your application sure for any kind of operation that you want throughout your application running period. Now it may be any kind of variables and suppose if you want to fetch some data from server then you can put your asynctask in application so it will fetch each time and continuously, so that you will get a updated data automatically.. Use this link for more knowledge....
http://www.intridea.com/blog/2011/5/24/how-to-use-application-object-of-android

Android : Persisting object(s) between BroadcastReceiver.onReceive() calls

I have an app that receives SMS and starts certain "work", now this work is done through Camera and some other third party APIs. So when I receive the appropriate START message (SMS) for my app, I start the work and it continues till the app receives STOP message from remote device.
The receiver is registered in the manifest.xml file and works fine otherwise.
Now the problem is, my app starts the work fine on receiving the START message, but when I receive STOP message after some time, I cannot really stop the work because the handles/object references I have for the camera and the third party API both are null. I do not have any control over either of them - and can't make them singleton. So I need to persist those object references between two calls of the BroadcastReceiver, and I can't figure out a way to do this properly. For now, I have just made these two static members of the class and it works fine, but it's not really a good solution. What's the best way to handle situation in this case? How can I use the initialized objects between multiple onReceive() calls of the BroadcastReceiver?
Any help/pointers would be highly appreciated!
TIA,
- Manish
You can't use singleton that class, but you can create a normal class and have it singleton. That class has a HashMap and stores your api and camera objects with a key. When you need to stop particular task, you can find it by some key and stops them by that object.
When you start the task store that object in that singleton and when you want to stop that find that object from the hashmap and stops/dispose the task.
I suggest you to create a singleton object volatile.
private static volatile Utils _instance = null;
public static Utils Instance() {
if (_instance == null) {
synchronized (Utils.class) {
_instance = new Utils();
}
}
return _instance;
}
You can also add the object reference in the ApplicationClass i.e. a class extended from Application class. your application class persist in memory until any Activity or Service is running. It will only killed after all the Activity and Service killed.
I think this is a better approach that Static field.
But this is also not Full-Proof. I am also searching for this problem.

is it possible to access one class file to access its methods or variable by a service and another by an activity AT THE SAME TIME?

I have a class named PatientDetails in which i am storing the values from the xml and then need to access its variables and method from the service as well from the activity at the same point of time ??
This is a typical multi thread scenario. You can do it without any troubles as long as you are just reading the data.
If you are reading the data from patient details class through your activity and writing data to it through your service you will get into run time exceptions. You have carefully synchronize the variables or methods in such cases.
One way to share a 'helper' class is to hold a 'static' reference to a single instance of it in the Application component of your app. Example...
public class MyApp extends Application {
public static detailsHelper;
#Override
public void onCreate() {
detailsHelper = new PatientDetails();
}
}
When you need to use the 'helper' in any other component such as an Activity or Service you simply reference it by the Application name as follows...
MyApp.detailsHelper.doSomething();
Technically speaking, under default conditions there is no such occurrence of two components accessing something at the same time because an Android Application and all of its components exist within a single process with a single thread of execution.
You should be very careful, however, if any of the components execute code which uses threads. For example, an Activity using an AsyncTask or perhaps using an IntentService which creates its own worker thread to do work. In this case, make sure any methods in the 'helper' class which write data, do so in a thread-safe manner.

Categories

Resources