Differences between a service and a singleton instance? - java

I'm developing an android application, and would like to know the difference between a service started with startService() and a singleton class performing the same code I put in startService().
So, for example if I have a VideoRecordingService service set to record a video from the camera on it's start, and a CameraRecorderClass singleton class which have a StartRecording() method that also records a video from the camera, how do they differ?
They both non-related to any activity lifecycle, and they both use the main thread to do it's work.
Thanks

Service is mainly used when you want to do some background operation. For eg:- Playing music in your application. So, if you don't have any Activity running you can play music using Service.
While your Singleton instance would not be working if you close your application/activity if unless you are performing it in some background task. Also, Service will restart automatically if you return START_STICKY from onStartCommand when your Service is killed due to some reason.
So, in your case if you really want to do some long background running operation then its better to use Service instead of your Singleton instance.

When using startService it creates a new instance of that class, it can have a context and do a wide range of things that the Service class inherits. You can create this anywhere in your application where you have a context, and you can start and stop it multiple times (using startService and stopSelf)
With a singleton class, well, its a static object that you can only have once instance of (unless you want to create more I guess?). The static object can isn't much different, however it doesn't have a context and all that nice android stuff that comes with a class (unless you pass it a context or what ever you may need).
A service can also be run without needing to invoke it by using a activity, or showing a UI, it can run in the background with no UI, and can be started using a broadcast listener without interrupting the user, as long as the service is running then the service shouldn't be automatically closed by the system, rather then if you started an async task in the singleton and then closed the activity and the activity was destroyed.
There may be more to it. But you would have to look into dalvik..

Related

Comunication between a running android service and a recyclerview adapter inside the same service

So I have a foreground service displaying a few items, I want to perform some function in the enclosing service when I press on an item in the recycler view. I'm aware I can use an Instance of the service, but it's a memory leak. I'm aware as well of the binding/unbinding methods between service and activity, but this I believe doesn't apply to my situation?
Normally everything you would like to execute in the Service should be implemented and then called using a Binder (if Service and App are in the same Process) and its onBind() method.
In your specific case I suppose your Service is the "owner" of the UI created by WindowManager (like a floating window), so:
if Service and UI are in the same Thread, you can pass a Listener/Callback to it or use the common onBind() way
if Service and UI are in different Theads: you need some kind of synchronization between them (Looper+Message, a Queue, etc...)
if Service and UI are in different Process: you need to implement "AIDL" technique

How to run service class in background continuously Even app crash (swipe the app to kill)

In my application i am using service class and activity class,where i am updating array list values for every minute in service class and showing it in activity class using callback method in service class.
I am updating array list values in onStartCommand() , return Service.START_NOT_STICKY; and its working fine but when i killing the application by swiping aside application is starting form starting stage(losing previous data) and service is stopping at certain time.
For that i tried to use return Service.START_STICKY, when i used START_STICKY its working fine with continuously update in service class.but when i killing the application by swiping aside, showing error in callback method.
Thanks in advance.
I think your approach is not the proper one as you won't be able to run service in the background for an infinite time in Android Oreo. You should consider using Firebase Job Dispatcher which can be used to run a block of code after regular intervals.

Android HandlerThread in singleton

I am writing an SDK that allows a user of the SDK to request data and have it returned to them asynchronously.
To access the SDK I decided to use a Singleton pattern. I do this because they may want to use the SDK from several different activities or fragments and I want each component that uses it to have the same instance. So the user will call MyClass.getInstance() which will return an instance of MyClass to them. Then they can call myClass.doAsynchronousOp(), etc...
One issues I am having is that when a user calls a method on the SDK it will do a bunch of work and I don't want to block the caller's thread. So, the solution I came up with was to create an instance of a HandlerThread when the class is first instantiated. Then when the user calls a method on the singleton class that is supposed to be asynchronous I create a Runnable and run it using the HandlerThread. This seems to work pretty well, but I have a few questions:
1) Let's say the user gets an instance of my singleton and calls one of the asynchronous methods. Now the class is holding a running HandlerThread. When the activity is destroyed is it imperative that I call .quit() on my HandlerThread? If so, I pretty much need to make the user call a method like myClass.unregister() in the onDestroy() method of they're activity which is ok, but I'd rather be able to do it automatically for them. Is it bad practice to not call .quit() on my HandlerThread when the application component holding it gets destroyed?
2) Since this is a singleton I'm noticing that even if the Activity that is holding it is destroyed, the instance can remain in memory. So if the Activity is destroyed and then recreated (device rotation) then my constructor of the singleton doesn't get run again. This is problematic because I setup my HandlerThread in the constructor. If I call .quit() on the HandlerThread when the Activity gets destroyed and then the activity gets recreated, the HandlerThread still exists in the singleton object, but now it's in the Terminated state and I can't use it. Is there a good way around this?
Maybe a more general question: How can I provide asynchronous access to my SDK without running into thread lifecycle vs. android component lifecycle issues?

Dedicated Android Activity to initialize data and libraries for the application

My app makes use of various heavy libraries and data files, that need to be loaded / synchronized with local storage on start-up. As this operation takes some time, I was thinking of creating a dedicated activity for this purpose. This activity would be the entry point of the application and would do the following:
Display a background image and progress bar
Process necessary data (and updating the progress bar accordingly)
On completion, launch a new activity
Here is a couple of questions:
My initialization activity needs to pass a reference to the data to its child activity. Ordinarily I would do this with setSerializable, but here I am using 3rd-party non-serializable classes.
So I was thinking of simply making the data static. Is this a good solution? Any chance the static reference might break when switching activities or during the application life-cycle?
public class LibraryInitializer {
private static Some3rdPartyClass myLib;
public static void initialize(){ // Called by initialization activity
myLib = Some3rdPartyClass.create();
}
public static Some3rdPartyClass getMyLib(){ // Called by child activity
return myLib;
}
}
I need the initialization activity to be called only once. How to prevent that it is shown again when a user clicks on the back button?
More generally, is this approach okay, or would you suggest a better one? (I also considered using one single activity, but adding/removing the progress-bar and background dynamically)
Long running code really ought to be done using Android services. I would recommend doing your complicated logic in a service that your various "Activity" classes (which correspond to the views of your application) simply consume. Services can outlive the UI of the application and can also be started / initialized in response to various other events (like system boot), even when the user is not interacting with the application whereas an Activity is very tightly intertwined with the presentation.
In terms of loading / syncing data, I would strongly recommend against putting this logic in your activity code... instead, use a SyncAdapter or one of the other scheduling mechanisms for syncing. This will ensure that syncing activity is batched with other uses of the networking chip, which minimizes overall battery usage, and also allows you to have synced before the user is actively using your application, so that you aren't keeping the user waiting when they open your app.
When you start a new Activity from the loading Activity call the finish() method to close that activity and it will be deleted from the applications activity stack. like below:
startActivity(intent);
finish();
For the question for passing data through activities, extend the Android Application class, where you can define the global state and variables of your application.

What is the best equivalent of a main() function for an Android app?

I've searched everywhere a manner to have the equivalent of a main() function (yes function not method) inside a Android application but failed...
Typically what I would want to do is:
void main()
{
// do some really nice initialisations stuff here
// ... let the app does his life, I really don't care
// do some final stuff here before leaving
}
The nearest approach I've seen so far is to use a SplashScreen and override the OnCreate() method. The problem is that is not acceptable from my point of view.
Why? Because a SplashScreen is nothing than an Activity tagged as a LAUNCHER.
That makes it to appear in the apps list, thing I don't want when I develop an app widget.
Furthermore, where to place my code just before the app destroy? In the onDestroy() method?
No, once again, this is not reliable. Android can decide to delete my instance whereas the application is still running.
Well, in fact, I take for principle that every components of my app are running in the same process since I don't mention explicitely in the Manifest that I wan't a component to run in its own process.
In the case of an app widget, I've placed my init code on the first call of onUpdate() method. I think it's a good bet. Then this app widget (AppWidgetProvider more precisely) is in charge to launch any activity as its will.
The "DataBase" for all the app is defined in a separate Singleton like this:
public class MyDataBase {
public static MyDataBase getInstance() {
if (instance_ == null)
instance_ = new DataBase();
return instance_;
}
public void load();
public void save();
static MyDataBase instance_ = null;
public int myInt;
public String myString;
public Object myObject;
etc..
}
With this Singleton I'm sure at least, its lifecycle is the same as the entire app itself.
To back with that AppWidgetProvider, I have to trick a little. Indeed, Android can decide to delete its instance whereas some other activities are still on place and the process is still running. So for example, systematically loading my DataBase in the first call of the OnUpdate() is unnecessary and overkill. What I do is having a static boolean value that indicates if the DataBase have been loaded for the lifecycle of this process or not.
Thus, the AppWidgetProvider can be instanciated tons of time, as long as the Singleton DataBase persists (so the process), it will not reload the DataBase each time, got it?
(yes difficult to be clear...)
About the cleanup code of the app, I thought to override the finalize() method of my DataBase Singleton, but well, I'm really not sure it's a good idea since the moment of the call of this method is totally unpredictable. I suppose it would be called if you suddently power off your Android, but well I'm not sure of anything here, thus so far, I didn't found a solution for that part.
Any comment or something less tricky that what I currently do is welcome.
Thanks.
onResume() is the function that will be invariably reached before starting you app, so you could either put the 'main' code in the onCreate() method or the onResume().
onPause() is ALWAYS called before destroying the app, either by the user or the OS.
There is great explanation regarding the lifecycle in the Android documentation:
http://developer.android.com/training/basics/activity-lifecycle/starting.html
For the initialisation you can over-ride the onCreate method of the Application class:
Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created. Implementations should be as quick as possible (for example using lazy initialization of state) since the time spent in this function directly impacts the performance of starting the first activity, service, or receiver in a process. If you override this method, be sure to call super.onCreate()
Termination is harder to deal with. You'll probably have to monitor each component of your application separately. If you are targeting API level 14 or later you can use Application.registerActivityLifecycleCallbacks to help with this.
The nearest approach I've seen so far is to use a SplashScreen and
override the OnCreate() method. The problem is that is not acceptable
from my point of view. Why? Because a SplashScreen is nothing than an
Activity tagged as a LAUNCHER.
It's because Android is formed with several activities and those activities have life cycles. So every activities start from onCreate() then finishes at onDestroy().
http://developer.android.com/training/basics/activity-lifecycle/starting.html
That makes it to appear in the apps list, thing I don't want when I
develop an app widget. Furthermore, where to place my code just before
the app destroy? In the onDestroy() method? No, once again, this is
not reliable. Android can decide to delete my instance whereas the
application is still running.
In a scenario that user presses home button to exit from your app, your current activity is more likely to invoke onPause() method (only when the activity has no other processes to finish). However, when user force closes (terminates) your whole application by ending process. Then you don't have to worry about invoking any methods or what so ever because Android itself will close anything related to your application automatically.
To back with that AppWidgetProvider, I have to trick a little. Indeed,
Android can decide to delete its instance whereas some other
activities are still on place and the process is still running. So for
example, systematically loading my DataBase in the first call of the
OnUpdate() is unnecessary and overkill. What I do is having a static
boolean value that indicates if the DataBase have been loaded for the
lifecycle of this process or not. Thus, the AppWidgetProvider can be
instanciated tons of time, as long as the Singleton DataBase persists
(so the process), it will not reload the DataBase each time, got it?
(yes difficult to be clear...)
The example you have posted for singleton database connection is not bad I think, but there are better ways to get the job done cleanly and more effectively. For example hibernate framework connection pooling

Categories

Resources