When onTrimMemory is called in a service - android

I have a START_STICKY service and each time when I pause the activity (when I minimize) service is calling onTrimMemory. I wanted to know, in what and all scenarios this callback will be called. Its only during App minimize(the activity onPause)?

The callback can be called in app_visible and app_hiding conditions, but the important thing is that when the onTrimMemory(int i ) is called, you must be ready to react to the situation.
The different meanings and occurrences of the method and its argument i can be found in the documentation.

Related

Android - onStop() will be called with a delay

I found my activities onStop() method will be called with a less than 10 seconds delay. I've never seen before this behavior.
Note :- The activity is singleTop and it starts with Intent.FLAG_ACTIVITY_REORDER_TO_FRONT flag.
Note :- I'm using Build Tools v23.0.2.
The delay wasn't before and the method would be called immediately.
I am guessing that you are starting another activity and you expect the current activity to receive an onStop() callback. According to the activity lifecycle, the onPause() method is called before the onStop(). In some cases onSaveInstance() is also called before the onStop() method. Additionally, when you call the startActivity or the startActivityForResult (again, I am assuming that is why you expect the onStop to be called), depending on the parameters that are passed, if those parameters need to be calculated/fetched/etc, it may take a while before the system can execute the startActivity, which would be the earliest that Android would initiate the life cycle calls. In the absence of any code here, it is not possible to see what else is getting executed before the onStop is called. I suggest you check the timeline for the code execution time, starting with the startActivity and when onStop is called, maybe by logging the timestamps for each call, starting with the timestamp just before the startActivity call, ending in the timestamp at the start of the onStop, to see where time is spent. I also suggest to simplify this by making sure that all parameters to the startActivity or startActivityForResult are previously set to their values, if that is not already the case.
You can fix the problem by either adding noHistory:true to the activity in the manifest file or by setting the flag programmatically. I had the same problem and this fixed it for me.
In my case, I stop video player when onStop() invoked, but the onStop() invoke has a 10s delay.
You can use something like eventBus, RxBus to post a event in the
Application.ActivityLifecycleCallbacks {
//post event here.and check the activity's Name in my targetActivity which play my video.
onActivityStarted()
}
I had the same problem. When I started an activity with startActivity(), onStop() was called exactly 10 seconds after onPause().
In my case, the activity being launched had a fragment, which had a WebView. I have no idea why, but if I removed following line, the delay was only around 2 seconds.
webView.setScrollbarFadingEnabled(false);
I have just faced this issues, after debugging there is a case that AdView (Admob banner) causes this issue.
In activity A (which is placed an adview) i start activity B. Back to A from B and onPause of B call immediately but all stop/destroy take 10s to be called. Remove the ad banner then everything get back normal.
Just post this case here for anyone to ref.
May be emulator is slow today
but onStop() should be called at once as single command
no onPause() or anything is called before this

android: Why onDestroy not be called when i call finish?

In my code i call finish on a activity but the onDestroy method of this activity not be called. would anyone can tell me why? when the onDestroy method will be called?
onDestroy() is called only when system is low on resources(memory, cpu time and so on) and makes a decision to kill your activity/application or when somebody calls finish() on your activity.
So, to test your code() you can make a test button, that will call finish() on your activity.
I believe you don't need to call all this stuff in onDestroy() until adap is not a critical resource. And even in that case android system has mechanisms to properly dispose them.
For More Details you can Refer Here

Delay between bindService() and onBind() when starting a Service

I'm facing a strange problem with my app. I have a LocationService that runs in the background. The way I manage its lifecycle is:
In onResume, every activity uses bindService(intent,serviceConnection, BIND_AUTO_CREATE) like that the service is automatically created when needed.
In onStop, every activity uses unbindService(serviceConnection)
This works because when switching activities, the new Activity onResume is called before the old Activity onStop method
The problem I have is, lets say I start from the home screen and I launch the app with an Activity that has a fragment in it. The order of the function call is as follows
Activity onCreate --> setContentView is called here
Activity onResume --> here bindService is called and should create the Service
Fragment onResume
Service onBind method is called
My question is why is there a something else between my bindServiceand onBind calls?? I have a feeling this has something to do with threading issues.
Well, this isn't a very good answer, but why wouldn't there be something else between your bindService() and onBind() calls? You seem to be assuming that when you call bind the system will immediately create and start your service, and no such guarantee is provided.
You haven't indicated whether yours is an IntentService, or just a regular Service, and this might affect the speed with which your service is launched, but my answer would be the same.
Also, I'm assuming that your ServiceConnection object is called, as expected, sometime after your service's onBind() returns.
I say this not based on having read anything definitive, but because I had a similar experience: I was surprised and annoyed at how long it took before my service was created and my ServiceConnection was called, even though I returned from the service's onBind very quickly. (My fragments needed data from the service to create the initial UI so any delay in the creation of the service meant a delay in displaying the initial UI to the user.)
In the end I settled upon launching my service using an Intent rather then a bind, e.g.
Intent si = new Intent( this, com.company.MyService.class );
si.setAction( MyService.SVC_BIND );
startService( si );
I then sent MyService.SVC_UNBIND in place of calling unbind. When I received the UNBIND intent in my service I cleanup and then call stopSelf(). These are user actions - I just named them for how I'm using them.
I believe this was faster, but looking back upon my comments from that code I don't have any specifics. Note that this meant no ServiceConnection, but I'm making some direct calls from the activities into the service, and using LocalBroadcastManager a fair bit.
Another option to consider (in order that your service be started more quickly, if that is your goal here??) is to launch it in Appliction.onCreate(), rather then waiting for Activity.onResume(). All of these options make it necessary to do some extra work to determine when to stop the service, compared to your current, normal, scheme where that is taken care of for you.
In my case, my issue was using android:process attribute for <service> element within Android Manifest, which is supposed to improve performance, but in reallity, maybe it does once the service is running, but it takes a very long while to reach onCreate() (and so also to reach onBind()). For me it was taking minutes. Now Apps and services run smooth and as expected.
More info:
https://developer.android.com/guide/topics/manifest/service-element

Android onCreate or onStartCommand for starting service

Usually when I create an Android service I implement the onCreate method, but in my last project this does not work. I tried implementing onStartCommand, and this seems to work.
The question is: when I have to implement a service which method is required? Which methods I have to implement? onCreate, onStartCommand, or both? And what is the role of each?
onCreate() is called when the Service object is instantiated (ie: when the service is created). You should do things in this method that you need to do only once (ie: initialize some variables, etc.). onCreate() will only ever be called once per instantiated object.
You only need to implement onCreate() if you actually want/need to initialize something only once.
onStartCommand() is called every time a client starts the service using startService(Intent intent). This means that onStartCommand() can get called multiple times. You should do the things in this method that are needed each time a client requests something from your service. This depends a lot on what your service does and how it communicates with the clients (and vice-versa).
If you don't implement onStartCommand() then you won't be able to get any information from the Intent that the client passes to onStartCommand() and your service might not be able to do any useful work.
Service behave same like Activity Whatever you want to associate once with a service will go in onCreate like initialization
and whenever the service is called using startService. onStartCommand will be called. and you can pass any action to perform . like for a music player , You can play ,pause,stop using action
And you do any operation in service by sending an action and receiving it on onStartCommand
onCreate work like a Constructor.
Edit in Short
onCreate() calls only for the first time you start a Service Whereas onStartCommand() calls everytime you call the startService again. It let you set an action like play,stop,pause music.
public void onStartCommand()
{
if(intent.getAction.equals("any.play")
{
//play song
}
else if(intent.getAction.equals("any.stop")
{}
}

Is that possible onCreate is called more than onDestroy in Android?

In Activity, I register receiver in onCreate and unregister it onDestroy. It should works fine if every onCreate is followed by onDestroy after the next onCreate. Otherwise, if onCreate is being called more than onDestroy, receiver is registered multiple time and the app mis-behaves.
So my questions are:
Is that ok I register receiver in onCreate and unregister it in onDestroy?
Is that onCreate is always followed by onDestroy before next onCreate?
onDestroy is not guaranteed to be called:
http://developer.android.com/reference/android/app/Activity.html#onDestroy%28%29
"
protected void onDestroy ()
Added in API level 1
Perform any final cleanup before an activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.
Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
"
You may also want to look at this thread:
Activity OnDestroy never called?
onDestroy is called when the activity is being destroyed. Or removed from the back stack, when ever the user doesn't want it or there is no possible way to get back to it. When your activity wants to receive a broadcast that is fine to do it how you are. If there are no dialogs appearing or notifications or toasts appearing after you receive that should be fine also, if you want to be on the real safe side and only have one activity receiving at a time, and only while the activity is visible move these to onResume and onPause.
You could probably some how unregister when another activity has been brought to the front and re-register after?

Categories

Resources