Bind service to activity or fragment? - android

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

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.

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.

Android Service > Activity > Fragment with ViewPager

First, I'd to state that I've been searching for a solution for this problem for three days now, that may means either I'm not asking the right question or not using a good approach. If any, please guide me in the right direction.
This is the scenario: I've an Activity and a bound Service. The Service holds some data and processes it as necessary while posting a persistent (ongoing) notification with some information. The Activity has three Fragments inside a ViewPager that displays the data processed by the Service.
The Fragments are a List Fragment, that shows the active data entries available, a Details Fragment that displays the details for each data and a Parameters Fragment where the user can modify how the data is processed.
[Service] <-> ([Activity] -> [ViewPager([List], [Details], [Parameters])])
Everything works just fine. My Activity binds to the Service, the ViewPager is created after and then the Fragments fetch information trough an Interface.
Here comes the fun part... Screen Rotation!
As the Service binds asynchronously, when the user rotates the screen the Fragments no longer have the data because the Activity is bounding the service while they're already present and not recreated thanks to the ViewPager.
I've been trying to figure this out but it seems that I don't have the knowledge to solve it. I've tried making static references to the fragments, setting them up before the service is rebound but I can't get a stable solution.
I'd be using android:configChanges in my manifest but there are different layouts for each orientation.
Again, if I'm using a bad approach, please, guide me!
Difficult to suggest when I don't know your code but thinking out loud....
Can you have a "worker fragment" that is never displayed (i.e headless) and has setRetainInstance(true) set so it does not lose any state you have set.
Your worker fragment would bind to the service instead of the activity and maintain a reference to it.
If you need to communicate with your Activity, you can do this with callbacks.
Your other fragments could communicate with the worker instead of the Activity.
This process would basically make the activity little more than a shell into which the rest of your components are hosted. Rotation would lose nothing because all data is held in the retained fragment.
During the screen rotation process the activity is completely destroyed and use of android:congfigChange is discouraged. but what you can do is you can override saveInstanceState(bundle) method in which you can save the data present in your activity at the time it is destroyed by the system in response to the screen rotation. and later receive it as the system passes the bundle to the activities onCreate(bundle) method or get it from the restoreInstanceState(Bundle) method.

Android: Starting intent service within fragments

I have multiple fragments within an activity. Every fragment has to display some data that is fetched from the server using REST. I have been implementing IntentService with a corresponding receiver for REST requests. Right now I am able to do this by making fragments as inner class within the activity.
The problem I have with inner class is, on orientation change, an error is thrown like "cannot instantiate fragment, no empty constructor". For this problem, on search I found answers like either make the inner class static or create a standalone public class for Fragment. I still don't understand why would this happen on orientation change.
Now if I take the approach of creating a separate standalone class for Fragment, I will have to pass the activity object around to do startService and registerReceiver. And I do not want to use AsyncTask for this, as in my app I perform multiple REST requests within a single fragment and IntentService allows a broadcast to be sent after every request so that I do not have to wait until all the requests are finished to start loading the screen. And I feel it is not ok to pass activity object to a fragment. Shouldn't the fragment be as loosely coupled as possible with the activity so that same fragment can be used within multiple activities? If yes, what would be the best approach in resolving this?

Should the "sub"-activities in a TabActivity bind services?

I am building an application based on a tabbed activity. There are about 12 tabs at any given time.
I have built a download service, for my own use, which requires binding to it. I've found a few questions about the issue binding Services from tabs, but I haven't found anything discussing the best way to design this.
My paths seem to be:
Bind the download service in the tab's activities using getParent() or getApplicationContext() as the context to bind to.
Bind the download service once in the TabActivity and then expose it via a static method to other Activities making up the tabs.
Redesign the download service so that it does not require binding. (I'm not really sure this is a viable option or buys me much)
I'm basically in a toss up between 1 and 2. It seems like #1 seems to make the activities more independent, but I'm not sure if its going to cause problems having the tab "sub" activities binding the same service 12 times on the tab activitie's context. Similarly, I'm not sure if it is good practice to expose state-dependent objects, like a Service, via a static method to other Activities. I'm concerned it may create a number of race conditions that need to be accounted for depending on when the binding happens and when the tab activities are started.
What seems like the better design?
The main purpose of a service is to run long term tasks in the background, even being able to live longer than the app that started the service. By the description on your downloadservice, it seems like it's only handling short term actions, during the lifetime of your app. Therefore I would recommend creating a singleton DownloadManager class that can manage the caching and handle the downloads using worker threads.
I would design this using Context.startService() instead of binding. In my mind, when you bind, you are tying the lifecycle of the service to the lifecycle of the binding activity. If the lifecycles aren't related, you should instead use startService().
If you use startService, you can simply send out a broadcast whenever a download completes to notify the activities (or to update progress) and when all downloads have completed, you can call Service.stopSelf() to shutdown the service.
You can have single activity for all of 12 tabs and change the content/view based on current tab. You can bind the service to the activity object. I think this approach is relevant as all tabs are dealing with same kind of task. Use something like
public class LifeLine extends TabActivity implements TabHost.TabContentFactory {
public void onCreate(Bundle savedInstanceState) {
TabHost tabHost = getTabHost();
TabHost.TabSpec spec
spec = tabHost.newTabSpec("Day").setIndicator("Day",
res.getDrawable(R.drawable.icon))
.setContent(this);
tabHost.addTab(spec);
...
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String tag) {
if ("Day".equals(tag)) {/* Change the view as needed.*/
view.setDuration(1);
} else { /* Change the view as needed.*/}
view.invalidate();
Log.v("life", tag);
}
});

Categories

Resources