Can a service access a variable within an Activity? - android

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.

Related

FirebaseMessagingService's onBind method is final. how make it bound service?

I want to bind my custom firebase service to the MainActivity class. if it was a normal service, it would be easily done by making the service implement the onBind method, but it is not available because this method is set final in the superclass of FirebaseMessagingService class. I want to bind the service in order to use the LiveData variable set inside this class in the MainActivity class.
I have searched for best practices here and read this documentation about bound services but no luck. I tend to use LiveData somehow but I feel it is not working until I somehow manage to bind the service. am I missing something?
As suggested in a comment by #CôngHải, I can use a singleton object with LiveData inside it to communicate between service and activity without the need of binding the service to activity.

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.

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

Android: Access method in an activity from another activity

My launch activity starts up another activity whose launch is set to single instance. In this 2nd activity, I have a public method. I then start up a 3rd activity and that activity needs to access the public method in the 2nd activity. I don't want to use startActivity and pass it extras because I assume the onCreate will get called (or am I wrong?) and I need to avoid the 2nd activity from reinitializing itself.
When an activity is started using startActivity, is it possible to gain access to the underlying class instance itself and simply call the method?
I actually came up with a simple solution. As a matter of fact you can access the underlying class of an activity. First, you create a class that is used to hold a public static reference to activity 2. When activity 2 is created, in its onCreate method you store "this" in the static reference. Activity 2 implements an interface with the methods that you want available to any other activity or object. The static reference you hold would be of a data type of this interface. When another activity wants to call a method in this activity, it simply accesses the public static reference and calls the method. This is no hack but is intrinsic to how Java operates and is totally legitimate.
It is not a good idea.
As I can understand method from second activity is actually not connected to particular activity while you want to call it from another one. So carry the method out to other (non-activity) class (maybe static method) and use it from both activities.
It's not directly possible to gain access to activity object started using startActivity (without using some hacks). And frankly you shouldn't even trying to accomplish this.
One Activity component can cycle through several Activity java object while its alive. For example, when user rotates the screen, old object is discarded and new activity object is created. But this is still one Activity component.
From my experience, when you need to do things you described, there is something wrong with your architecture. You either should move part of activity's responsibilities to Service or to ContentProvider, or use Intents, etc. Its hard to recommend anything more specific without knowing more details.
No there is no way to pass a reference via startActivity() however you can use some sort of shared memory to keep reference to your Activity. This is probably a bad design. However passing an extra with your Intent will not cause onCreate, that is completely related to the lifecycle.

Android IntentFilter for Every New Activity?

Is it possible to register a global broadcast receiver that gets notified every time a new activity is started (either by startActivity, startActivityForResult, etc)? What would the IntentFilter be?
EDIT: Just to clarify, I don't mean across apps I mean within my own app
You could potentially create your own partial subclass of Activity where it overrides onCreate(), onStart(), etc and manually calls a static/singleton instance of your global receiver as appropriate. After that, just derive your own activities' implementations from that subclass.
However, I'm assuming the reason you want to do this is that the "receiver" actually contains or otherwise represents some globally available state or resource - if you can find a way to implement your application without having any global state (and just passing it along as payload for an activity call, for instance), that would be best.
No, there is no way to do that.

Categories

Resources