I have a fragment and a service that is called by the fragment.
The fragment contains a gauge, and the service uses a device's microphone to meausure sound. I would like the gauge to reflect the sound.
Is there a way for me to transfer the sound value from the service to the fragment?
I have tried to send the gauge object from fragment to the service through a parcelable, but because the gauge is from a custom library, I cannot parcelize or serialize it. I have also tried to create a custom class with just an int attribute, sending the object from the fragment to the service, hoping that updating the int attribute in the service would update the int in the fragment, but it didnt work out.
I want this update to be happening at each second of the measurement, so sending the information OnDestroy of the service does not work for me.
Do you have any suggestions on how I could do this? Thanks
For Communication between service and fragment, you have to create boundService.
Implementing TimerTask in service for each second will solve problem of updating value.
Note: we can use liveData of sound value in service and register its observer in fragment so whenever timertask update value in livedata object it will reflect in fragment.
Related
I have a scenario that i have one activity and 4 fragment , from one of the fragment i am passing the data using interface to the main activity , I am receiving the value or say object , now what i need to do , i have to pass the same object to all other fragment . but i don't wanna to use bundle or static method/field , I just want to know the best idea or approach to this question , what i can do ?
One solution i am thinking using the abstract class , Let's say my abstract class name is ParentFragmentAbstarct should implements the Fragment class and define a abstract method inside it let say setData(), then every Fragment should extends this Fragment class then abstract method is overridden in every fragment , now i am lost , how to set the value in it if i am getting the value only from one of the fragment(let's say from network response i am receiving the data in Fragment 2 n now how to set this same value in other three fragment)
Using Abstract Class with an Array of Fragment Object:
Like ViewPager you have an Adapter holding the instances of those fragments. When one of your fragments informs the MainActivity about the new data using Interface then you can simple iterate on ViewPagerAdapter and call your abstract Method. All the fragments will get notified.
Using Broadcast Receiver
You can declare your own broadcast receiver and made your fragments to listen to those broadcast. when the data is ready, your fragment can send a broadcast and all the other Fragments who are listening to this specific broadcast can thereafter update their state. Check this one
Using Observable RxJava
In ReactiveX an observer subscribes to an Observable. Then that
observer reacts to whatever item or sequence of items the Observable
emits. This pattern facilitates concurrent operations because it does
not need to block while waiting for the Observable to emit objects,
but instead it creates a sentry in the form of an observer that stands
ready to react appropriately at whatever future time the Observable
does so.
have a look at observable
Using EventBus
EventBus is a publish/subscribe event bus for Android and Java.
This is a great library, very small footprint and gets the job done with ease
You could create a singleton data manager class, and have all the fragments subscribe to it and listen for data changes. Each fragment can then have it's own implementation when recieving a state change.
Make any database calls in this manager class and distribute data to the listeners on response callbacks
I have an AppUtils class which handles my network requests. In my activitys onCreate i call the function that initializes a singleton from xml. All it does is make async https post request with okhttps3's enqueue to a server and deserialize the XML response to pojo(singleton).
public static void initSingleton(String apikey)
The activity also has a viewpager with 3 different fragments, the fragments all have different views and the goal is to populate the views with the data from the singleton.
What is the best way to notify the fragments when the initSingleton is done doing its work so i can update the views accordingly?
If i simply do Singleton.getInstance().getWhatever() to get a certain value in the fragments onCreateView, the Singleton is obviously not initialized yet, so it gives me a nullpointerexception.
I tried passing a Handler to the function and send a message when the request is finished. It works but i'm only able to notify the activity and not the fragments.
Would appreciate any help on this.
Cheers
edit: Is there a more elegant solution than doing it via. handler and then updating the fragment with an interface? Maybe EventBus/Otto?
edit2: Ended up realizing it with EventBus, surprisingly easy and the library is pretty small.
Otto/Eventbus can do the stuff for you.
Localbroadcast manager is also one of the option, no need of any new library dependency in this case.
I am writing an Android App and i need to display some results from a non-activity class.
Basically my App gets the current location, activity and other things, and on those i run some functions, for example to check if the user has been at that place before.
Anyway, an intent triggers these functions, and at the end of the function I want to update a TextView with the result of these functions.
But it doesn't seem to work from anywhere besides MainActivity. I tried making the TextView static, but that doesn't seem to work, and returning the results to MainActivity is not possible either in since it is not called directly from MainActivity.
Does some have an idea on how to solve this problem?
This is my first android project, so there's still a lot of thing i don't know about. Thank you!
I don't know exactly what your code looks like, but do you have a model class that holds all your data (for example, some kind of singleton)? If so, you could just save the updated text there, and then update the TextView in a callback method.
If that doesn't fit what you're doing, I would considering refactoring your code so that the text you want is sent back to your MainActivity. You mentioned that the method is not called directly, but could your calculations pass the text to an intermediate class, which passes it to your MainActivity?
You should not update the ui drom background thread.
If you want to update the ui from background thread use Handlers,AsyncTask or use some other thread concepts.
If you want to update the UI fro Service or Broadcast receiver for eg you receive a message inside onReceive of broadcasrReceiver now to update the ui use sendBroadcast and inside your activity registet a dynamic Broadcast receiver and then update
I have an Activity StaggeredPrenotaTour starting a second Activity Details through an Intent, the class Details contains an AsyncTask class ReservationTask, and after some operations to the network, it has to pass a Java Object back go the StaggeredPrenotaTour class.
StaggeredPrenotaTour at the point where it starts Details:
Intent message = new Intent(staggeredPrenotaTour, Details.class);
message.putExtras(bundle);
getContext().startActivity(message);
Basically I need pass my Object to the current context of StaggeredPrenotaTour, so that I don't have to create a new instance of it but update the contents of the current one!
Unfortunately I've read that there is no way you can get a Context from an Intent, so how is another way to get the working instance of StaggeredPrenotaTour inside Details class?
so how is another way to get the working instance of StaggeredPrenotaTour inside Details class?
You don't.
so that I don't have to create a new instance of it but update the contents of the current one!
It sounds like these two activities should share a common data model, perhaps implemented via a singleton manager. StaggeredPrenotaTour can use the revised data in its onResume() method, which will be called as part of it coming back into the foreground after Details is destroyed (e.g., user presses BACK).
Or, use an event bus (LocalBroadcastManager, greenrobot's EventBus, Square's Otto, etc.). Have ReservationTask raise a ReservationResultsEvent that StaggeredPrenotaTour subscribes to, so StaggeredPrenotaTour can find out the results of the work.
Starting another activity doesn't have to be one-way. You can also
start another activity and receive a result back. To receive a result,
call startActivityForResult() (instead of startActivity()).
For details, read the guide on developer.android.com
Suppose I have an Activity that's a list. It calls a Service when this Activity starts. The Service will do background stuff--download, parse, and fill the list.
My question is this: How can the Service communicate with the Activity?
How can I call a method in the Activity, from the Service? (I'm new to OOP)
The Service is started like this:
hello_service = new Intent(this, HelloService.class);
startService(hello_service);
One of the things my service does is download and parse an XML. After that, it needs to fill a list! So, I want to pass the parsed stuff back to the Activity, and call a method in the Activity to fill that list.
I recently asked a very similar question, best way for service that starts activity to communicate with it, that got a very helpful answer.
Also, consider using AsyncTask instead of a service if the service doesn't need to be alive when the activity is closed. Then you don't need to bother with the server/activity-communication.
You can set activity object to service and invoke methods of your activity from service. But you must to care about thread-safe when you update your UI.
Hope this helps! Tutorial