How to get notified about activity's lifecycle - android

I'm writing a helper class for my activity, which uses an external service. Like in a standard design pattern regarding bound services, I want to bind on activity creation and unbind on activity destruction. However, I want to isolate this logic to my helper class, so that activity would only use an instance of that helper and don't call bind and unbind explicitly.
I can pass the activity to the helper class, but I cannot find any way to schedule a callback on activity's lifecycle's events - there's just no such methods in Activity class. While this most probably means that I cannot achieve what I want to, and also that it's probably not a good idea, I still want to ask the community about this. Is it possible? Is it a good idea? Is it possible to achieve similar results with some other classes (not the Activity)?
I'm new to Android development and I'm seeking for the best practices. Any ideas are appreciated.
Thanks!
EDIT: Basically, I want to be notified on activity creation and destruction. I want to be able to schedule a callback on onCreate and onDestroy methods, but from outside of the Activity. Those methods are protected and therefore inaccessible from other classes.

You can use the Application.ActivityLifecycleCallbacks class. Keep in mind that the class was introduced in API level 14. For lower versions you could make hook methods in your library and require that the target Activity will call the appropriate hook method from its corresponding lifecycle method. Of course, this would be a very fragile implementation.

Lifecycle methods are the means to implement behaviour which will be executed when DalvikVM decides to do something with Activity (pause/resume/create/destroy), not to invoke that behaviour artificially.
If you want to externalise logic in helper/controller of some sort and be able to use service connection do initialization within ServiceConnection handler.
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,IBinder service) {
...init helper here...
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
...shutdown helper here...
}
};
then handle connections as usual.

Related

What is faster Communicating, sending broadcast VS calling activity method directly in Android?

In my app, I have to call an activity method from the fragment.
I know I can do this in two ways:
1. Via sending a broadcast to activity:
Intent intent = new Intent("FILTER");
intent.putExtra("EXTRA", 1);
sendBroadcast(intent);
2. Or Calling the activity method directly:
((MyActivity) getActivity()).method();
I would like to know which way is faster and safe to communicate. Any help would be appreciated.
Thank you.
Loosely Coupled Fragment?
I am not sure about the speed. But on the design perspective You should use an interface to communicate with an Activity rather calling Activity method directly from your Fragment. ie ((MyActivity) getActivity()).method();
Because using an interface makes your Fragment independent from your
Activity. Let's say in future you want to use your fragment in Some
other Activity then you will not have to change anything in your
Fragment.
Interface
public interface Somelistener {
public void someMethod();
}
Your Loosely coupled Fragment
YourFragment extends Fragment {
Somelistener listener;
public void onActivityCreated(Context context){
listener = (SomeLisner)context;
}
public void buttonClick()
{
listener.someMethod();
}
}
So if you are using in your MainActivity. No problem
MainActivity implements SomeListener{
#Override
public void someMethod()
{
// Activity method
}
}
In future you want to use Fragment in SomeOtherActivity. No problem
SomeOtherActivity implements SomeListener{
#Override
public void someMethod()
{
// somethother method
}
}
BroadcastReceiver Approach?
TBH I have seen this approach for Service-Activity Communication. Not for Activity - Fragment communication.
For communicating between Fragments and the Activity that contains it, there's actually a much better 3rd option.
The better option is to use an Interface as a callback method. This is described very well in this documentation: https://developer.android.com/training/basics/fragments/communicating
Using an interface is much more preferred over your two methods because it's both safer and more efficient.
For your first method of using Broadcast Receivers, this is actually a very inefficient solution due to Broadcast Receivers not being meant for a task like what you're after.
Let me quote you something from the Android documentation:
Warning: Limit how many broadcast receivers you set in your app. Having too many broadcast receivers can affect your app's performance and the battery life of users' devices. For more information about APIs you can use instead of the BroadcastReceiver class for scheduling background work, see Background Optimizations.
https://developer.android.com/guide/topics/manifest/receiver-element
So yes, Broadcast Receivers will have a bigger effect on your app's performance and the device's battery life over the other method you suggested and the method I suggested.
Additionally, don't forget that a Broadcast Receiver is meant to listen to broadcasts. The type of Broadcast Receiver you're using in your example is actually a Global Broadcast where you didn't explicitly limit it's "range", so any Broadcast Receiver could potentially "listen" in to your broadcast. In terms of security, using a Global Broadcast like this isn't safe either.
You also don't want other apps to potentially fire off a Broadcast that coincidentally coincides with your app's Broadcast Receiver, causing it to receive data not meant for it and crashing due to this accidental and coincidental naming.
Honestly, there's more potential issues of using a Broadcast Receiver in a way it's not meant for.
As for your second method of directly calling the Activity's method... this is actually very inefficient for managing code. You're basically tying the Fragment tightly together with that specific Activity.
However, Fragments, by design, makes it common to be swapped into other Activities or Fragments... you'll basically have to do multiple if statements and casts each time you want to run code from it's parent.
Also, keep in mind that if you later change code in MyActivity, it can cause problems for this fragment due to you forgetting how tightly bound it is to the Activity.
But if you use the more preferred Callback Interface approach, it's simply a middleman meant to deliver a "Hey, DO something for me" message. Quick and direct. It's also plays friendly with any Activity or Fragment you want to attach this Fragment to later since those Activities or Fragments simply have to implement the Interface and the callback bridge between both parent and child is formed.
It is better to use interface to communicate from fragment to activity rather than a Local broadcast.
Activity will implement the interface and fragment will call the methods.

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.

Can a service access a variable within an Activity?

I have an Activity called MainActivity that starts a Service called MainService. It is also binds the Service, so MainActivity can access methods and public variables within MainService. Is it possible to do it the other way round, i.e. the Service is able to access the Activity's methods?
I wish to implement it this way because I have a variable in MainActivity that is set upon onResume(), and on first startup the service has not yet started by the time onResume() runs, so at that point in time the service is still null.
This answer assumes that the Service in question runs in a different process:
Yes, it is possible. The general idea is that not only your Activity binds the remote Service through some AIDL defined interface, but it also implements additional AIDL interface which the Service is aware of, and sets itself as a callback target of the remote Service.
You'll have to have 2 AIDL files: the first one describes the interface of the Service, and the second one describes the interface of the Activity.
The implementation of such a scheme is very similar to "remote Service callbacks" described in this answer, though "callback" method would no longer be void, but return the value you're interested in.
Design considerations:
The above scheme will allow you to get values from Activity, but I don't think you should take this path. From the description of your use case, it looks that you only want to pass some value to the Service when Activity gets resumed. Since your Service is bound anyway, you can simply add a method setSomeValue(int value) to its AIDL definition and call this method from onServiceConnected() callback.
Yes it's possible.
You have to prepare method in your service to return back your activity just after service is bound:
public void bindActivity(MyActivity activity){...}
Then after service is bound to activity just call this method with MyActivity.this as parameter.
However...
You probably should not do it. Much more clear solution is using LocalBroadcastManager to pass events and data or use some more efficient solutions like Otto to do this same, but still - without direct access to one component's fields / methods from another.

Bind service to activity or fragment?

I am working on a music player app. I have a main activity which has multiple fragments, each displaying songs on the device album wise, artist wise etc..
I have a music service which handles all the playback and other stuff.
What I'm confused about is the binding of this service with various fragments I have.
Right now I'm binding the main activity and each fragment individually with the service and its working pretty much fine. But I was wondering if this is really the best practice? Is there any way to just bind the main activity with the service and then some how use it in its child fragments?
I maybe missing some very basic concept of activity or fragments or services. So someone please guide me in this regard.
I guess it's more of a conceptual question so any code isn't needed. But still if it's required then please let me know.
EDIT :
My question is: What would be a better way to bind a service with an activity with multiple child fragments(each of which would be using the service)?
Bind the Service to your activity and not the Fragment. The description of your application, one activity with multiple Fragment that are swapped in and out, makes this the most (and really only) practical approach.
When you bind a Service to an Activity you are tying its lifecycle to that of the Activity. See Bound Services. Each time you add or remove a Fragment in your activity that Fragment is created and destroyed. You do not want to try to link a service to this process because then you would have to create and destroy the service each time a new fragment is created or destroyed.
Instead bind to the host Activity. You can then interact with your host activity from your fragments with an interface to access the bound service or by Intent.
I think the cleaner architecture is to bind directly from the fragment. Regarding the problem outlined in Rarw's answer, you can bind to the service from your activity and from your fragments too. This way you are sure that the service will be there until the activity is not destroyed.
I can see two main advantages in connecting from the fragment:
Service connection is async, so inside the fragment you are never really sure that the service you are getting from the activity is not null. This will lead you at least to some null pointer checks and to some mechanism to refresh the fragment both when it's created and when the service connects (so you are sure you will display the data no matter which of the two happens first).
You do not depend on the particular activity your fragments lives in. To get the service from the activity I think you are doing a cast to the activity specific class. You could create an interface like BoundActivity with a method like getBoundService to obtain the service from it, but I think it's an overhead considering the advantage of point 1. And what if you have multiple services.
UPDATE
Here is a very simple project showing this.
https://github.com/ena1106/FragmentBoundServiceExample
You can access your activity from a fragment by getActivity()
you can tray using the event bus pattern with this library , eventbus publish/subscribe pattern.https://github.com/greenrobot/EventBus check the project site for more information.
you can send events from/to service to active or fragments
IF you need to get some data from your service to your fragment at the beginning of the fragment lifecycle, the onServiceConnected on activity could not be called yet, mainly when you rotate your device, and you'll get a NPE.
I think is a good idea let fragment make his own connections since the service is started with startService() and not with bindService().
I bind service in My Host Activity,and pass Ibinder's object by Bundle which is setted in arguments.
and my code may like this:
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
//put service in bundle
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
};
The only method I have found to be reliable is to use a loader in Fragment:
create a Loader in the fragment
use the context of the Loader (set to activity in initLoader at when the Fragment's onCreate is called)
bind the service in onStartLoading, using a ServiceConnection which calls forceLoad() as soon as the service is bound
optionally register callbacks in onStartLoading/onStopLoading
unbind the service in onStopLoading

Implement ComponentCallbacks to listen for onConfigurationChanged

There is ComponentCallbacks interface in android using by activity, ActivityGroup, service etc. They implements it and someone notify them when activity configuration changed. So, I want to create my own class which implements ComponentCallbacks listens for onConfigurationChanged and doing some actions... So my class is implementing, but... I guess I need to register my class in someone's observer.
So, is it possible? Is there any ways to "register" my own class to be notified when configuration changed?
I guess this someone may be ActivityThread and it's method collectComponentCallbacksLocked. But I did't see here any ways to register my own class.
ActivityThread and
ComponentCallbacks using
p.s. Of course I can override activity's method onConfigurationChange change and then call the onConfigurationChanged method of my class, but I don't want. I want to know if there is any way in android to do it.
In the "Google I/O 2012 - Doing More With Less: Being a Good Android Citizen " talk (which you can find on youtube), it's explained that you can do this by calling Context.registerComponentCallbacks.
So, you just make your class implement the ComponentCallbacks interface (or ComponentCallbacks2 as you wish), the methods that you can override are added automatically, and from your Activity, Fragment.. just pass the instance from your class to register to it. Something like this:
registerComponentCallbacks( mYourClass );
That should do the work :)
According to #Sandra's answer we can use Context.registerComponentCallbacks to register our own component callbacks in the system and use it like this:
context.registerComponentCallbacks(new ComponentCallbacks() {
#Override
public void onLowMemory() {
// make some operations when system memory is low
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// make some operations when configuration has been changed
}
});
All our registered callbacks will be called when system configuration changed / on low memory.
Method registerComponentCallbacks available from API level 14. Checkout how it works here
What you want to do is to register a BroadcastReceiver to receive this braodcast Intent:
Intent.ACTION_CONFIGURATION_CHANGED
That event is broadcast by the system any time the configuration changes.

Categories

Resources