Status Update
Comments
ad...@google.com <ad...@google.com> #2
ch...@smartdata.net <ch...@smartdata.net> #3
@Override
public void onCreate() {
super.onCreate();
if (CoreHelper.apiLevel() >= Build.VERSION_CODE.O) {
final Context ctx = MyApplication.getinstance().getApplicationContext();
final NotificationCompat.Builder builder = NotificationHelper.getInstance().getNotificationBuilder(ctx);
final Notification n = builder.setLocalOnly(true)
.setVisibility(Notification.VISIBILITY_PRIVATE)
.setCategory(Notification.CATEGORY_SERVICE)
.setPriority(NotificationCompat.PRIORITY_MIN)
.build();
MyApplicationLogger.writeTraceEntry(TAG, "Starting foreground service and passing notification: " + n.toString());
startForeground(3, n);
}
MyApplicationLogger.writeTraceEntry(TAG, "Service started!");
}
When I start the service on 8.0 I see *BOTH* of the above messages in the log but then 5 seconds later, I still get android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground().
Again, the same code running on 8.1 does not produce this behavior. Unfortunately, we have over 1,100 users running 8.0.
ch...@smartdata.net <ch...@smartdata.net> #4
ch...@smartdata.net <ch...@smartdata.net> #5
ch...@smartdata.net <ch...@smartdata.net> #6
su...@swiggy.in <su...@swiggy.in> #7
pv...@swooby.com <pv...@swooby.com> #8
I've got clients actively crashing because of this, and I don't want to have to hack my code to delay all service stops by X seconds (ANR timeout).
ch...@smartdata.net <ch...@smartdata.net> #9
da...@gmail.com <da...@gmail.com> #10
onReceive of BroadcastReceiver class fires startForegroundService and service class calls startForeground in onStartCommand.
Is there any suggested flow for notifications? Or we need to go back to target sdk 25
[Deleted User] <[Deleted User]> #11
if (Build.VERSION.SDK_INT >= 26) {
String CHANNEL_ID = "my_app";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"MyApp", NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("")
.setContentText("").build();
startForeground(1, notification);
}
pv...@swooby.com <pv...@swooby.com> #12
My app used to get 80 crashes a day due to this bug.
I reverted the code to use Context.startService(...) instead of Context.startForegroundService(...).
My app now *only* gets 10 crashes a day due to "Not allowed to start service Intent ...: app is in background".
The above recommended solutions do not work for my use case.
I am no longer willing to accept 10 crashes per day, so my only solution now is to revert back to a compileSdkVersion/targetSdkVersion of 25, which requires rolling back support library to v25.4.0 (which will probably never see any future patches).
All of this, including the silence, is pretty ridiculous.
ch...@smartdata.net <ch...@smartdata.net> #13
pv...@swooby.com <pv...@swooby.com> #14
What crashes are you still getting? I would expect that you are still getting "Not allowed to start service Intent ...: app is in background", which is my current situation since I commented out my call(s) to startForegroundService due to this bug/crash/issue/feature.
st...@yahoo.com <st...@yahoo.com> #15
After your excellent comment about the flows above (#6) - i.e. with suggestion that after initial startService()/startForegroundService(), one still needs to do startForeground() in not only onStartCommand(), but also onCreate() (in fact in both - not just one or the other).
But in (#9) you were saying that did not fix the issue - and still getting crash reports.
Were you able to get the crashes on your devices as well - or it is a rare event that you could only see in the user crash reports (which makes it harder to debug) ?
Is it possible that some code flow paths are leading to startForeground() not being called ? For example you are toing stopService() before code has opportunity to do a startForeground() - as outlined in this thread:
Context.startForegroundService() did not then call Service.startForeground()
Is it possible some of the crash reports are from issues related to BOOT_COMPLETED handling in Oreo (also being problematic).
Are there any devices reporting this error which are pre-Oreo (I saw one comment on stackoverflow which suggested they were seeing on some Nougat version also) ?
pc...@gmail.com <pc...@gmail.com> #16
st...@yahoo.com <st...@yahoo.com> #17
This means that even if you do stopSelf() in the Service, you have to have done startForeground() ahead of that - which would seem like a waste (i.e. setting up notification and calling startForeground() with that).
This means all program flows have to be examined to ensure that once you do onStartCommand() you never wind up not having done startForeground(). Perhaps this is what causes the rare occurrence of crashes (which are not observable while testing yourself, but do show up on Google Analytics etc.).
Some stackoverflow threads suggest a workaround - where even if you do stopSelf(), you do startForeground() just before that:
st...@yahoo.com <st...@yahoo.com> #18
>This is a good thread where Ian Lake of Google explains it this way - basically once you do startForegroundService(), you have to do startForeground(). And if you cannot do startForeground() in your Service, then you better do that type of checking in your Broadcast Receiver etc. instead - so that you only start Service when are sure will do startForeground() there.
Here it is:
pc...@gmail.com <pc...@gmail.com> #19
So what I think is happening here is sometime due to busy CPU, after calling startFroregroundService; onStartCommand is being called 5 or more seconds later. It as per design.
But if it is not guaranteed that onStartCommand will be called within 5 seconds then there is no point of having this condition.
Now one solution I am going to try is remove startFroregroundService calls and use messenger to communicate with service, perhaps this will aloow me to reduce crash rates.
va...@gmail.com <va...@gmail.com> #20
// starting the service
if (VERSION.SDK_INT >= VERSION_CODES.O) {
context.startForegroundService(intent())
} else {
context.startService(intent())
}
// the Service onStart callback
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (VERSION.SDK_INT >= VERSION_CODES.O) {
startForeground(-1, getNotification())
}
return super.onStartCommand(intent, flags, startId)
}
va...@crunchyroll.com <va...@crunchyroll.com> #21
// starting the service
if (VERSION.SDK_INT >= VERSION_CODES.O) {
context.startForegroundService(intent())
} else {
context.startService(intent())
}
// the Service onStart callback
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (VERSION.SDK_INT >= VERSION_CODES.O) {
startForeground(-1, getNotification())
}
return super.onStartCommand(intent, flags, startId)
}
se...@gmail.com <se...@gmail.com> #22
[Deleted User] <[Deleted User]> #23
pv...@swooby.com <pv...@swooby.com> #24
my...@gmail.com <my...@gmail.com> #25
[Deleted User] <[Deleted User]> #26
All I really do is delay stopService by the ANR timeout, and cancel the delay if the service is restarted again.
This might suffice for my needs, but it does mean that the service will always take 5 seconds to stop.
Boo!
I will also be trying a "Bound Service" to see if that eliminates the need for this hack.
pv...@swooby.com <pv...@swooby.com> #28
So, perhaps folks that are running in to this bug could work around it by refactoring their code to use a Bound Service instead.
The refactor itself is not too difficult, but it may require non-trivial changes to your own surrounding business logic code.
to...@gmail.com <to...@gmail.com> #29
If a service is started with Context.startForegroundService it have to call startForeground even if it stop instantly and before the ANR time.
This was validated by Ian Lake and Framework team.
Documentation is missleading and I asked for a very long time that they update it
But as some others have reported here there's some real issues where you correctly do everything and there's still ANRs with Intent Services. (
Fun part is that I discussed about that with Wojtek Kaliciński from Google at a conference and he said he was absolutely not aware of this issue :)
So let's hope one day information does spread correctly.
eg...@crunchyroll.com <eg...@crunchyroll.com> #30
to...@gmail.com <to...@gmail.com> #31
My issue is that I have to keep a legacy Intent Service that is used by other apps as a public API so not sure I can do anything about that except break the API for all consumers and use something else :(
vl...@gtempaccount.com <vl...@gtempaccount.com> #32
le...@gmail.com <le...@gmail.com> #33
pc...@gmail.com <pc...@gmail.com> #34
pc...@gmail.com <pc...@gmail.com> #35
ct...@google.com <ct...@google.com> #36
Re #31, publishing a Service that other apps can start directly is fundamentally unsafe. You can mitigate that a bit by treating *all* start actions of that service as requiring startForeground(), though obviously that may not be what you had in mind.
pc...@gmail.com <pc...@gmail.com> #37
Hi
pc...@gmail.com <pc...@gmail.com> #38
pc...@gmail.com <pc...@gmail.com> #39
declare it anr even if in first line of onstartcommand that app os calling
startForeground then whose fault is this. So Google can you please stop
bragging and really start working on real issuea if you want to be
everywhere. Its very bad behaviour..
On Fri 25 May, 2018, 11:40 PM , <buganizer-system@google.com> wrote:
to...@gmail.com <to...@gmail.com> #40
I'm well aware of the issue and do everything correctly see
The main post is indeed a known issue but doc is not clear enough, I did ask for update of the docs since months
For non native English speakers "promise" and "before it start" and very far from must in all cases....
So as tried to explained to multiple times to Googlers. there's false issues reported by users because of incomplete documentation but there's a real issue with ANR even when doing everything correctly.
So please take time to see Wojtek Kaliciński and actually try to believe that not all devs are dumb and that sometimes there's issues at OS level ;)
pv...@swooby.com <pv...@swooby.com> #41
We are following the docs.
It *is* a framework bug.
Please fix it. Pretty please. With a cherry on top.
I've moved on my converting my code to use a bindService.
The problem still persists for those that can't, especially if they are working with legacy services that they cannot bind to.
ch...@smartdata.net <ch...@smartdata.net> #42
pc...@gmail.com <pc...@gmail.com> #43
pc...@gmail.com <pc...@gmail.com> #44
st...@googlemail.com <st...@googlemail.com> #45
ni...@shipwell.com <ni...@shipwell.com> #46
pv...@swooby.com <pv...@swooby.com> #47
This bug has a clear repro.
Without seeing/knowing the code, there has got to be some stupid timer that starts when "Context.startForegroundService(...)" is called and ONLY stops when "Service.startForeground(...)" is called.
There are many code paths that will need to cancel any timer started by startForegroundService, the most obvious being startForegroundService (in the case of multiple calls) and stopService (in the case before startForeground can be called).
[Deleted User] <[Deleted User]> #48
The issue is exposed via crash reporting. Interesting note, out of tens of thousands of users, here are the only platforms reporting the crashes:
Devices 100% Google
Pixel 2 XL 40%
Pixel 2 28%
Pixel 23%
Pixel XL 9%
[Deleted User] <[Deleted User]> #49
onCreate() is most likely incorrect as well, unless you're certain that it will be called every time your intent is started by a startForegroundService() call.
It also is not necessary to call startForegroundService from code that is already running in the foreground -- for example, when you're calling from a service that is already in the foreground, you can just use startService() instead of startForegroundService(), and avoid the need for an additional notification, etc.
Although there does appear to be some evidence that a framework issue may exist, I suspect it is not to blame for **all** of these crash reports some of you are having.
zx...@gmail.com <zx...@gmail.com> #50
Calling context.startForegroundService from App widget and the very first thing I do in BOTH onCreate and onStartCommand is startForeground a notification with non-zero ID. And I had checked all possibilities I swear the only place where stopSelf is called is faaaaaaaaaaaar away from onCreate and onStartCommand.
I have nearly 10k active daily users and receive over 100 of this crash every day, all from 26 and 27 devices. And #37 told us that 28 still carries this issue because googler refuse to even understand that it is their fault. #36, man, seriously, IF FRAMEWORK CAN NOT GUARANTEE STARTING SERVICE WITHIN 5 SECONDS, WHY IN HELL YOU CRASH IT WITHOUT CHECKING IF YOU HAVE GOT YOUR OWN JOB DONE?
ma...@marcardar.com <ma...@marcardar.com> #51
to...@gmail.com <to...@gmail.com> #52
I tried to continue my conversation with the Googler on Twitter to have this reopened but he have now vanished and no more answers. So I guess they just don't care and we'll have to live with this.
How different from Google IO where they say we values devs, devs feedback is important, and all the bla bla bla.
ma...@marcardar.com <ma...@marcardar.com> #53
pv...@swooby.com <pv...@swooby.com> #54
I'm the OP.
Then the 30+ of us that have stared this issue should consider this just a conversation as to how we can open the next one so that they will accept it.
I opened this bug with code reproducing a variant of the problem.
I don't know how I could have made it more clear.
How can we made the next bug we open be the one they take?
pv...@swooby.com <pv...@swooby.com> #55
ct...@google.com <ct...@google.com> #56
The outright semantic issue, that it's simply an error to kick something off with startForegroundService() but neglect to actually transition it to foreground via startForeground(), is just that: a semantic issue. That's treated as an app bug, intentionally. Stopping the service before transitioning it to foreground is an app error. That was the crux of the OP, and is why this issue has been marked "working as intended."
However, there are also questions about *spurious* detection of this problem. That's *is* being treated as a genuine problem, though it's being tracked separately from this particular bug tracker issue. We aren't deaf to the complaint.
pv...@swooby.com <pv...@swooby.com> #57
Respectfully, it is infeasible to expect app developers to have 100% deterministic control of the timing of when Context.stopService(...) is called in an app.
Other threads may be calling it on a non-deterministic behavior, especially for apps that frequently update their single "ONGOING" notification w/ text/status updates.
If an app calls Context.startForegroundService to update the notification and then needs to immediately update the notification text again, it is completely reasonable to and just might be calling Context.stopService before calling Context.startForegroundService a second or more time.
Context.stopService *MUST* cancel any and all timers that were started in Context.startForegroundService.
Thank you for responding and acknowledging that Google is treating this as a genuine problem.
Can you please cite the particular bug that you are tracking so that I can watch it and not spam any other closed bugs or open duplicate bugs to get attention on this issue?
Thank you.
pv...@swooby.com <pv...@swooby.com> #58
This seems like faulty logic to me and should not be a decision that the Android OS makes.
There are many legitimate reasons why a Context.serviceStop(...) may be called before Service.onCreate() or Service.onStartCommand(...) have a chance to be called and themselves call the required Service.startForeground(...).
Perhaps the service receives an intent with an extras payload that decides inside onCreate or onStartCommand to show or not show the notification or even just call stopSelf!
In this case, requiring the service to always call Service.startForeground after Context.startForegroundService is called means that the service needs to pass a dummy/throwaway notification to Service.startForeground(...) and cannot call stopSelf.
It is infeasible to require every app call to Context.startForegroundService(...) to be paired with a call to Service.startForeground(...).
Whoever thought this was a good idea needs to seriously reconsider reverting this whole concept/requirement.
ar...@gmail.com <ar...@gmail.com> #59
sa...@gmail.com <sa...@gmail.com> #60
bz...@gmail.com <bz...@gmail.com> #61
pv...@swooby.com <pv...@swooby.com> #62
No response on what particular issue they *are* tracking, so only they know.
Translucency is apparently a myth.
bz...@gmail.com <bz...@gmail.com> #63
If I am in a dead end for my widget, do you recommend to open a new case?
or is it to be ignored again?
I think that you should rephrase: backward compatibility is a myth :)
pv...@swooby.com <pv...@swooby.com> #64
At first I was skeptical that this would be difficult, but after doing this 3-4 times it is pretty dead simple to convert over to a bound service and does not have any of this limitation/rules.
Simply expose a binding context that returns the service instance, and then in ServiceConnection.onServiceConnected save a reference to that service instance, and finally whenever you want to show the notification just call startForeground on that instance.
*Tomorrow* I will rewrite my sample code at
bz...@gmail.com <bz...@gmail.com> #66
I have a widget with multiple broadcast receiver.
Adding a dummy Notification with startforeground really helps.
I have 2 problems so far:
-starting a service associated to a button
-starting an alarm manager
My code works perfectly until N.
pv...@swooby.com <pv...@swooby.com> #67
All you need is to bindService when your app starts up and save a reference to that bound service instance.
Your service is already started so you no longer need to call Context.startService just to call Service.startForeground.
Just call startForeground directly using the reference to your bound service instance.
If you do a lot of other work in your existing/legacy service code then just move all of your code out of your Service's onCreate/onStartCommand methods in to separate methods and then just call those methods directly via the reference to your bound service instance.
vk...@gmail.com <vk...@gmail.com> #68
But startForeground() didn't work with bound service in my case, I was needed to start and bind it...
Anyway, I just made simple notification in a separate group, and looks like it works the same way so far.
ct...@google.com <ct...@google.com> #69
"If your service is started (running through Context.startService(Intent)), then also make this service run in the foreground....
Note that calling this method does not put the service in the started state itself, even though the name sounds like it. You must always call ContextWrapper.startService(Intent) first...."
[or startForegroundService(), of course]
pv...@swooby.com <pv...@swooby.com> #70
For now startForeground seems to be working for me on a bound service, but I can see AOSP deciding to change things to make this not work so that it matches the documentation instead of actually making developer's lives easier by stopping this incessant moving the line in the sand so that we can easily create foreground services as needed for our apps and without bugs.
Arguably, none of the changes over time that AOSP has made to lock down foreground services have helped or stopped whatever problem they were intended to solve.
Pretty please, with a cherry on top, just allow us to easily make foreground services without any blocking bugs!
Starting a timer in "Context.startForegroundService" and *only* stopped in "Service.startForeground" is ridiculous.
Whatever timer that is started in "Context.startForegroundService" needs to also be stopped in all exit/stop points of a Service, especially "Context.stopService" and Service.stopSelf".
That one change will fix a lot if not most of these problems.
[Deleted User] <[Deleted User]> #71
is there a non-closed issue on this where I should be reporting it instead?
to...@gmail.com <to...@gmail.com> #72
And will discover when P is out if they did something or not, that's the Google way ;) Like they ask you for P to report the internal things you use, then forget a part of them in the grey list but no more answers on the issue so you are on your own to deal with the breaking :)
The issue can be multiple cause but one is known for sure, the ANR timer starts when the caller calls, so if the system is busy and start your app 9.5 seconds after the call, your app have 0,5 second to fully initialize and call startforeground ;)
la...@livinideas.com <la...@livinideas.com> #73
[Deleted User] <[Deleted User]> #74
The net effect is "crickets" to us.
This is an "Android 26" issue, not an "Android P" issue, so there should be at least one public visible issue that we can reference, but there is not.
Highly unimpressed. :/
[Deleted User] <[Deleted User]> #75
I'm calling startForeground() in onStartCommand() of the service. The issue is not faced by all the Oreo users we have (only 1 so far).
Stack trace:
Fatal Exception: android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1881)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
ru...@gmail.com <ru...@gmail.com> #76
But for now, this weird crash has gone away.
What was causing the issue:
- I was starting the Service by calling the ContextCompat.startForegroundService(Context context, Intent intent)
Here is what this method does under the hood:
if (Build.VERSION.SDK_INT >= 26) {
context.startForegroundService(intent);
} else {
// Pre-O behavior.
context.startService(intent);
}
As you see - nothing special here. Just checks the SDK version and calls appropriate method. But wait a second!
This is the only way to start your Service if you're running Oreo and above
[At least, Google says. Otherwise exception will be thrown!]
As described in the documentation - exception will be thrown if we did not attach a notification by calling Service.startForeground().
To do so system gives us up to 5 seconds. If we don't - ANR - and then crash of the app.
Now, back to the ContextCompat.startForegroundService(Context context, Intent intent)
If you call this method (actually it calls Context.startForegroundService(intent)) which means that you 100% must attach the notification in your Service!
What I've done to fix this issue:
- In my case I was running a Service just with
Intent myIntent = new Intent(context, MyService.class);
intent.setAction("SomeAction");
to only handle this action in Service and stop the Service immediately when action will be handled, which, in my case,
takes not about 5 seconds, just milliseconds.
And then, was starting the service by ContextCompat.startForegroundService(context, myIntent)
But, by calling this method the crash has been throwing every single time.
So, I've changed starting of the Service
from ContextCompat.startForegroundService(context, myIntent)
to context.startService(myIntent) and the issue has gone away.
But my biggest surprise was that by calling context.startService(myIntent) on Oreo system does not produce an Exception!
Please, correct me if I am wrong, but by going this way we should not be able to start any Service on Android >= Oreo!
Unfortunately I am not sure if this fix will help you, but, at least, you may try.
[Deleted User] <[Deleted User]> #77
No, that is incorrect.
Of course you can still start a service with context.startService() on Oreo, if that context is in the foreground.
It will only fail if the call occurs when that context is in the background.
> As described in the documentation - exception will be thrown if we did not attach a notification by calling Service.startForeground().
That is only true WHEN using context.startForegroundService, which you only need to do IF you need to be able to start the service from the background.
If your app is running in the foreground, you can call startService the same as before.
And you can also call startForeground() from any service without first calling startForegroundService(), to make the service remain in the foreground. Same as before!
The only time startForegroundService() is required, is as step 1 of launching a service into the foreground *from the background*. (Step 2 is calling startForeground() which must be done within 5 seconds or the ANR will occur.)
If you need to launch a foreground service from a point where your app might not have foreground status, THEN you need to use startForegroundService() on Oreo, and THEN that service will need to fulfill the contract by calling startForeground() from a place that is guaranteed to be executed soon enough.
Much of this discussion has had very little to do with the issue originally brought forward, which is unfortunately being clouded by devs who seem to lack a fundamental grasp of what they're working on.
jy...@gmail.com <jy...@gmail.com> #78
This may avoid crash but the notifications are not getting generated anymore.
In order for notifications to be created, you need to run it in foreground for Oreo onwards.
So, it doesnt fix the code.
AM i missing anything?
pv...@swooby.com <pv...@swooby.com> #79
Are you referring to my "bind" workaround example, or something else?
I am seeing notifications just fine in my "bind" workaround example.
(although, as mentioned elsewhere in this thread, the documentation says that "Service.startForeground" should only be called on "started" services, so I suspect that it is only a matter of time before AOSP makes another change that breaks my bind workaround).
The problem with the true statement that you only need to call "startForegroundService" when your app is in the background should be obvious.
There is zero simple reliable OS provided API to know if you app is in the foreground.
Whatever test the startService is doing to know that the app is not in foreground is not available to us developers.
So, developers now need to hand roll their own solution to detect if their app is in the foreground (ex: add your Activity to a collection in onStart, and remove in onStop).
By our logic may be different from the OS startService logic, so we may test that we do or don't need to call Context.startService or Context.startForegroundService, and Context.startService may disagree.
So then we may just want to call Context.startService, and if that throws a known exception then call Context.startForegroundService.
All of these added layers upon layers upon layers of code all to allow the OS to prevent apps from abusing foreground services is ridiculous.
Some developers or PMs working on this area in AOSP are seriously not grounded in reality.
It would be like mandating that an automobile is not allowed to move until the seatbelt is buckled around every occupant.
There are tons of ways to get around any mandate, so the next version adds stricter mandates that still have some workarounds, so the next version adds even stricter mandates that *still* have workarounds.
The end result is a car that is a pain in the ass and zero fun to drive...and yet creative people can still find some way(s) to work around the mandate, although most of them are pissed off that they had to resort to just drastic workarounds.
Just let us simply and easily create foreground services like we always have!
:/
go...@gmail.com <go...@gmail.com> #80
pv...@swooby.com <pv...@swooby.com> #81
Example:
java.lang.IllegalStateException: Not allowed to start service Intent { cmp=
You have to call Context.startForegroundService(...) to keep from throwing that exception, and then your service has to call Service.startForeground(...) within ANR seconds in order to not throw android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
go...@gmail.com <go...@gmail.com> #82
pv...@swooby.com <pv...@swooby.com> #83
ct...@google.com <ct...@google.com> #84
go...@gmail.com <go...@gmail.com> #85
Today, 6:57 AM on app version 95253
Sony Xperia XZ1 (SOV36), Android 8.0
Type Version code API levels Target SDK
APK 95253 21+ 22
Image straight from my dev console showing the ANRs and my target levels:
go...@gmail.com <go...@gmail.com> #86
pv...@swooby.com <pv...@swooby.com> #87
Are you using support/appcompat?
If you use any third party libraries it is possible the may be overriding this.
go...@gmail.com <go...@gmail.com> #88
compileSdkVersion 26
buildToolsVersion '27.0.3'
defaultConfig {
applicationId "gonemad.gmmp"
minSdkVersion 21
targetSdkVersion 22
versionCode 253
versionName "2.2.11"
renderscriptTargetApi 21
whole list of dependencies:
compile 'com.google.android.gms:play-services-cast:11.0.4'
compile 'com.android.support:support-v4:26.0.0'
compile 'com.android.support:mediarouter-v7:26.0.0'
compile 'com.android.support:appcompat-v7:26.0.0'
compile 'com.koushikdutta.async:androidasync:2.+'
compile 'de.greenrobot:eventbus:2.4.0'
compile 'com.jakewharton:butterknife:6.0.+'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.sothree.slidinguppanel:library:2.+'
compile 'com.github.machinarius:preferencefragment:0.1.1'
compile 'com.rengwuxian.materialedittext:library:1.8.2'
compile 'com.squareup.okhttp:okhttp:2.5.0'
ma...@marcardar.com <ma...@marcardar.com> #89
buildToolsVersion '27.0.3'
go...@gmail.com <go...@gmail.com> #90
[Deleted User] <[Deleted User]> #91
Stack trace:
Fatal Exception: android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1780)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:172)
at android.app.ActivityThread.main(ActivityThread.java:6590)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I have used following code:
A. in Gradle
---------------------------------------------------------------------------------------------------------------------------
android {
compileSdkVersion 27
buildToolsVersion '27.0.3'
defaultConfig {
applicationId 'com.dummy'
minSdkVersion 21
targetSdkVersion 27
versionCode 130
multiDexEnabled true
versionName "2.30"
//testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
// todo: use for showing log into release apk
initWith(buildTypes.debug)
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
debug {
initWith(buildTypes.debug)
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
preprod {
initWith(buildTypes.debug)
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
useLibrary 'org.apache.http.legacy'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
android {
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
lintOptions {
abortOnError false
}
dexOptions {
preDexLibraries = false
javaMaxHeapSize "4g"
}
buildTypes {
debug {
//TODO: use for start debug app or not ... for start debug place "true" otherwise "false"
debuggable true
}
}
}
dependencies {
implementation('org.apache.httpcomponents:httpmime:4.3.6') {
exclude module: "httpclient"
}
implementation('org.apache.httpcomponents:httpcore:4.+') {
exclude module: "httpclient"
}
implementation('com.crashlytics.sdk.android:crashlytics:2.9.2@aar') {
transitive = true;
}
implementation('io.branch.sdk.android:library:2.+') {
exclude module: 'answers-shim'
}
implementation 'se.emilsjolander:stickylistheaders:2.7.0'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:support-vector-drawable:27.1.1'
implementation 'com.android.support:customtabs:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.twitter.sdk.android:twitter-core:3.1.1'
implementation 'com.twitter.sdk.android:tweet-ui:3.1.1'
implementation 'com.twitter.sdk.android:tweet-composer:3.1.1'
implementation 'com.twitter.sdk.android:twitter-mopub:3.1.1'
implementation 'com.google.android.gms:play-services-location:15.0.0'
implementation 'com.google.android.gms:play-services-maps:15.0.0'
implementation 'com.google.android.gms:play-services-fitness:15.0.0'
implementation 'com.google.android.gms:play-services-analytics:15.0.0'
implementation 'com.google.android.gms:play-services-auth:15.0.0'
implementation 'com.google.firebase:firebase-auth:15.0.0'
implementation 'com.google.firebase:firebase-messaging:15.0.2'
implementation('com.facebook.android:facebook-android-sdk:4.32.0') {
exclude group: 'com.android.support', module: 'support-v4'
exclude group: 'com.android.support', module: 'appcompat-v7'
exclude group: 'com.android.support', module: 'cardview-v7'
exclude group: 'com.android.support', module: 'customtabs'
exclude group: 'com.android.support', module: 'support-v4'
}
implementation 'com.android.volley:volley:1.1.0'
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'de.hdodenhof:circleimageview:2.1.0'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
implementation 'com.github.scottyab:showhidepasswordedittext:0.8'
implementation 'io.branch.sdk.android:library:2.17.1'
implementation 'com.bugfender.sdk:android:1.+'
implementation 'com.github.jd-alexander:LikeButton:0.2.3'
implementation 'com.github.freshdesk:freshchat-android:1.1.1'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.soundcloud.android:android-crop:1.0.1@aar'
implementation 'com.razorpay:checkout:1.4.1'
implementation files('libs/YouTubeAndroidPlayerApi.jar')
implementation 'com.github.bumptech.glide:glide:4.6.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1'
implementation files('libs/PGSDK_V2.1.jar')
implementation 'com.androidadvance:topsnackbar:1.1.1'
implementation 'it.sephiroth.android.library.targettooltip:target-tooltip-library:1.3.15'
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
implementation 'io.reactivex.rxjava2:rxjava:2.1.13'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.retrofit2:retrofit-adapters:2.4.0'
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
implementation project(path: ':myTracksLib')
implementation 'com.google.protobuf:protobuf-java:2.6.1'
implementation 'com.flyco.dialog:FlycoDialog_Lib:1.3.2@aar'
implementation project(':myTracksLib')
implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
implementation 'io.supercharge:shimmerlayout:2.1.0'
}
---------------------------------------------------------------------------------------------------------------------------
B. in Class
--------------------------------------------------------------------------------------------------------------------------
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
getApplicationContext().startForegroundService(new Intent(getApplicationContext(), DummyService.class));
}
else{
getApplicationContext().startService(new Intent(getApplicationContext(), DummyService.class));
}
----------------------------------------------------------------------------------------------------------------------------
C. in manifest
-----------------------------------------------------------------------------------------------------------------------------
<service
android:name=".Services.DummyService"
android:exported="false" />
--------------------------------------------------------------------------------------------------------------------------------
ra...@gmail.com <ra...@gmail.com> #92
pu...@gmail.com <pu...@gmail.com> #93
So there is something broken on P, with that clever timebomb kicking it when it should not, for incomprehensible reasons. I have tried to reprod it in the Android Pie emulator to no avail.
lb...@gmail.com <lb...@gmail.com> #94
pu...@gmail.com <pu...@gmail.com> #95
If anything, startForegroundService() is really a "feature" that is too clever for its own good and when it causes an unobvious crash, there is no way to understand what exactly caused that crash.
jm...@gmail.com <jm...@gmail.com> #96
to...@gmail.com <to...@gmail.com> #97
/**
* Similar to {@link #startService(Intent)}, but with an implicit promise that the
* Service will call {@link android.app.Service#startForeground(int, android.app.Notification)
* startForeground(int, android.app.Notification)} once it begins running. The service is given
* an amount of time comparable to the ANR interval to do this, otherwise the system
* will automatically stop the service and declare the app ANR.
*
* <p>Unlike the ordinary {@link #startService(Intent)}, this method can be used
* at any time, regardless of whether the app hosting the service is in a foreground
* state.
*
* @param service Identifies the service to be started. The Intent must be
* fully explicit (supplying a component name). Additional values
* may be included in the Intent extras to supply arguments along with
* this specific start call.
*
* @return If the service is being started or is already running, the
* {@link ComponentName} of the actual service that was started is
* returned; else if the service does not exist null is returned.
*
* @throws SecurityException If the caller does not have permission to access the service
* or the service can not be found.
*
* @see #stopService
* @see android.app.Service#startForeground(int, android.app.Notification)
*/
@Nullable
public abstract ComponentName startForegroundService(Intent service);
And it real workd it crash immediatelly, instead of "The service is given an amount of time comparable to the ANR interval to do this, otherwise the system will automatically stop the service and declare the app ANR."
ra...@gmail.com <ra...@gmail.com> #98
de...@observation.org <de...@observation.org> #99
[Deleted User] <[Deleted User]> #100
class ForegroundService : Service() {
companion object {
fun start(context: Context, notificationId: Int, notification: Notification) {
ContextCompat.startForegroundService(context, context.serviceIntent())
context.bindToService { startForeground(notificationId, notification) }
}
fun stop(context: Context) {
context.bindToService { stopSelf() }
}
private fun Context.serviceIntent() = Intent(this, ForegroundService::class.java)
private fun Context.bindToService(block: ForegroundService.() -> Unit) {
val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
block((binder as DirectBinder).service)
unbindService(this)
}
override fun onServiceDisconnected(name: ComponentName) = kotlin.Unit
}
bindService(serviceIntent(), connection, Context.BIND_AUTO_CREATE)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int) = Service.START_NOT_STICKY
override fun onBind(intent: Intent?) = DirectBinder(this)
class DirectBinder(val service: ForegroundService) : Binder()
}
vo...@gmail.com <vo...@gmail.com> #101
Thanks,
-Young
so...@gmail.com <so...@gmail.com> #102
he...@gmail.com <he...@gmail.com> #103
This problem happens even when you ensure to call startForeground() just after service started as Google documented. It may be because the service creation and initialization process already cost more than 5 seconds in many scenarios, then no matter when and where you call startForeground() method, this crash is unavoidable.
My solution is to ensure that startForeground() will be executed within 5 seconds after startForegroundService() method, no matter how long your service need to be created and initialized. Please go to stackoverflow to see the detailed code examples.
Hope this helps in your project. Good luck.
yo...@terralogic.com <yo...@terralogic.com> #104
@Override
public void onCreate() {
super.onCreate();
int NOTIFICATION_ID = (int) (System.currentTimeMillis()%10000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(NOTIFICATION_ID, new Notification.Builder(this).build());
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
int NOTIFICATION_ID = (int) (System.currentTimeMillis()%10000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(NOTIFICATION_ID, new Notification.Builder(this).build());
}
}
Thanks,
he...@gmail.com <he...@gmail.com> #105
yo...@terralogic.com <yo...@terralogic.com> #106
ro...@googlemail.com <ro...@googlemail.com> #107
ma...@marcardar.com <ma...@marcardar.com> #108
[Deleted User] <[Deleted User]> #109
private final void bringDownServiceLocked(ServiceRecord r) {
...
if (r.fgRequired) {
Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
+ r);
r.fgRequired = false;
r.fgWaiting = false;
mAm.mAppOpsService.finishOperation(AppOpsManager.getToken(mAm.mAppOpsService),
AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
mAm.mHandler.removeMessages(
ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
if (
Message msg = mAm.mHandler.obtainMessage(
ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
msg.obj =
msg.getData().putCharSequence(
ActivityManagerService.SERVICE_RECORD_KEY, r.toString());
mAm.mHandler.sendMessage(msg);
}
}
...
}
For more details and a workaround please check my SO answer:
[Deleted User] <[Deleted User]> #110
km...@lyft.com <km...@lyft.com> #111
From our breadcrumbs, it takes over 5 seconds for Android to start a foreground service.
...
27s before crash context.startForegroundService(new Intent(context, AppService.class));
21s before crash AppService onCreate
21s before crash AppService startForeground(notificationId, notification)
21s before crash AppService onStartCommand
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1881)
at android.os.Handler.dispatchMessage(Handler.java:105)
…
Foreground services are not a good way to declare new ANR exceptions. Issues unrelated to foreground services should not crash foreground services.
[Deleted User] <[Deleted User]> #112
ww...@gmail.com <ww...@gmail.com> #113
For other devices and other OS, I didn't see any crash.
I am attaching a screenshot for reference from Crashlytics (Firebase)
gb...@gmail.com <gb...@gmail.com> #114
ra...@comprovei.com <ra...@comprovei.com> #115
pv...@swooby.com <pv...@swooby.com> #116
Google/Android: Get your shit together, pretty please!
Fix issues like this and your god damn horrible Bluetooth/BLE stack!
a1...@gmail.com <a1...@gmail.com> #117
mi...@onfleet.com <mi...@onfleet.com> #118
"After having same issue with same phones, I have made few changes and the crashes were gone. I am not sure what made the trick, but I am guessing that calling
startForeground in both onCreate and onStartCommand. I am not sure why that is needed if service is already started and everything was called properly in onCreate.
Other changes:
- Changing serviceId to some low number (1-10)
- Calling startFororegroundService less often through a singleton synchronous class (this was implemented before with the crashes to prevent stopping service before it started with a callback from onStartCommand, but now it also filters calls if service already started).
- using START_REDELIVER_INTENT (shouldn't affect anything)
The issue has been happening on the mentioned phones just for some users, so I suspect it is related to some new update from Samsung and will eventually be fixed"
wa...@gmail.com <wa...@gmail.com> #119
ar...@gmail.com <ar...@gmail.com> #120
context.startForegroundService(new Intent(context, TaskQueueExecutorService.class));
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
This will crash with the same error. The Service will NOT start until the method is complete, therefore no onCreate() in the service.
So even if you update the UI off the main thread, IF you have anything that might hold up that method after it, it won't start on time and give you the dreaded Foreground Error. In my case we were loading some things onto a queue and each called startForegroundService, but some logic was involved with each. So if the logic took too long to finish that method, crash time. The old startService just ignored it and went on it's way and since we called it each time, the next round would finish up.
This left me wondering, if I called the service from a thread in the background, could it not be fully bound on the start and run immediately, so I started experimenting. Even though this does NOT start it immediately, it does not crash.
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
context.startForegroundService(new Intent(context, TaskQueueExecutorService.class));
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
I will not pretend to know why it does not crash. Maybe it does not allow the Service to get killed before it starts?
pu...@gmail.com <pu...@gmail.com> #121
Even if you call startForeground() as the first statement of onCreate(), if your onCreate() takes more than 5s to run (for whatever reason, including some initialization operations that take an unusual amount
of time possibly only in some scenarios or devices), you will get the dreaded error.
I have a clear crash report that shows this for one my user where the service onCreate() takes nearly 9s (instead of the usual < 2s) for an obscure reason.
da...@gmail.com <da...@gmail.com> #122
1) If you have a foreground service that restarts itself (START_STICKY) and the application is killing in the background by the OS (due to low memory, low battery or other reasons). The process will be recreated again, but you will get the "did not then call Service.startForeground" if your Application.onCreate() hasn't finished within about 4.8 seconds. Your Service onCreate/onStartCommand will be only called after Application.onCreate(), so you have no chance to promote the service into foreground. You must make sure that your Application.onCreate will never take more than 5 seconds to finish.
How to test: Add a Thread.sleep(5000) into your application.onCreate(), launch the app, put it into background (hit HOME) and kill the process from AS. Now wait for the Service/Process to relaunch and observe crash (100% reproduce rate).
How to fix: profile your application.onCreate and make sure it's quick (or delay work after onCreate).
2) You can also kill the process while application.onCreate is in execution and it will trigger the same error, but this should not happen during regular use.
pu...@gmail.com <pu...@gmail.com> #123
In my app I have an exit button (don't ask) that exits the app cleanly.
In that exit flow, a foreground service that runs for the lifetime of the app is stopped with stopService() resulting in onDestroy() is called on the Service.
Fine. But I have a few unexplained "Context.startForegroundService() did not then call Service.startForeground()" happening immediately after the service has been destroyed,
thrown in the main thread Looper. The only workaround I found for this issue, is to call System.exit() in the Service's onDestroy(), so whatever is later throwing that Exception has never a chance to run.
I'm still clueless how this can be happening as the Service in question has been started and startForeground() called in time.
pu...@gmail.com <pu...@gmail.com> #124
I still have crash reports and after re-reading this thread for the nth time, re-reading the Android docs and Service lifecycle again and again, re-read my code and spent (again) and afternoon trying to understand it...
I still have zero clue in which scenario this crash happen.
A user has contacted me and he can reproduce it semi-reliably but I've been absolutly unable to reproduce it on my test device.
This issue is maddening. I'll stop there.
ma...@gmail.com <ma...@gmail.com> #125
This api is so broken, I don't know why we even bother.
bo...@gmail.com <bo...@gmail.com> #126
I believe system re-create for some reason service and if it was marked before inside as foreground by Service.startForeground system thinking that startForegroundService() has been called to start it before?!
kr...@gmail.com <kr...@gmail.com> #127
em...@gmail.com <em...@gmail.com> #128
se...@gmail.com <se...@gmail.com> #129
al...@gmail.com <al...@gmail.com> #130
ni...@gmail.com <ni...@gmail.com> #131
th...@gmail.com <th...@gmail.com> #132
I got this exception in about 0.04% crash rate, even if in 5 seconds. you can see one of my custom logs by firebase crashlytics:
my firebase crashlytics custom log when crash occurs, 06:59:36 shows startForegroundService and 06:59:37 shows startForegroundFullOs:
# Crashlytics - Custom logs
# Application: com.***.***
# Platform: android
# Version: v1.1.5 (28)
# Issue: 307965107a8c83a894765f0f39ecf0b0
# Session: 5E408ED7026C0001144DADD100F1E758_DNE_0_v2
# Date: Mon Feb 10 2020 06:59:00 GMT+0800 (CST)
0 | Mon Feb 10 2020 06:59:36 GMT+0800 (CST) | D/ContextUtil startForegroundService
1 | Mon Feb 10 2020 06:59:37 GMT+0800 (CST) | D/SleepSamplingService onCreate
2 | Mon Feb 10 2020 06:59:37 GMT+0800 (CST) | D/SleepSamplingService startForegroundFullOs
3 | Mon Feb 10 2020 06:59:37 GMT+0800 (CST) | D/SleepSamplingService startForegroundFullOs
4 | Mon Feb 10 2020 06:59:42 GMT+0800 (CST) | D/AlarmForegroundService onCreate
5 | Mon Feb 10 2020 06:59:42 GMT+0800 (CST) | D/AlarmForegroundService startForegroundFullOs
6 | Mon Feb 10 2020 06:59:42 GMT+0800 (CST) | D/AlarmForegroundService startForegroundFullOs
7 | Mon Feb 10 2020 06:59:42 GMT+0800 (CST) | D/AlarmForegroundService startForegroundFullOs
8 | Mon Feb 10 2020 06:59:43 GMT+0800 (CST) | D/AlarmService cancelNotification, tag = AlarmForegroundService
9 | Mon Feb 10 2020 06:59:43 GMT+0800 (CST) | D/ContextUtil startForegroundService
10 | Mon Feb 10 2020 06:59:43 GMT+0800 (CST) | D/AlarmForegroundService onDestroy
th...@gmail.com <th...@gmail.com> #133
# Crashlytics - Custom logs
# Application: com.***.***
# Platform: android
# Version: v1.1.5 (28)
# Issue: 307965107a8c83a894765f0f39ecf0b0
# Session: 5E3C7D4401E500016644003F47E5ADCB_DNE_0_v2
# Date: Fri Feb 07 2020 04:55:37 GMT+0800 (CST)
0 | Fri Feb 07 2020 04:55:37 GMT+0800 (CST) | D/ContextUtil startForegroundService
1 | Fri Feb 07 2020 04:55:37 GMT+0800 (CST) | D/SplashActivity onCreate
2 | Fri Feb 07 2020 04:55:37 GMT+0800 (CST) | Splash_Show
3 | Fri Feb 07 2020 04:55:43 GMT+0800 (CST) | D/AlarmForegroundService onCreate
4 | Fri Feb 07 2020 04:55:43 GMT+0800 (CST) | D/AlarmForegroundService startForegroundFullOs
5 | Fri Feb 07 2020 04:55:44 GMT+0800 (CST) | D/AlarmForegroundService startForegroundFullOs
6 | Fri Feb 07 2020 04:55:44 GMT+0800 (CST) | D/AlarmForegroundService startForegroundFullOs
7 | Fri Feb 07 2020 04:55:44 GMT+0800 (CST) | D/SplashActivity onDestroy
8 | Fri Feb 07 2020 04:55:44 GMT+0800 (CST) | D/SplashActivity onCreate
9 | Fri Feb 07 2020 04:55:44 GMT+0800 (CST) | Ad_Result_Request
10 | Fri Feb 07 2020 04:55:44 GMT+0800 (CST) | D/AlarmService cancelNotification, tag = AlarmForegroundService
ct...@google.com <ct...@google.com> #134
For example, see #133:
0 | Fri Feb 07 2020 04:55:37 GMT+0800 (CST) | D/ContextUtil startForegroundService
1 | Fri Feb 07 2020 04:55:37 GMT+0800 (CST) | D/SplashActivity onCreate
2 | Fri Feb 07 2020 04:55:37 GMT+0800 (CST) | Splash_Show
3 | Fri Feb 07 2020 04:55:43 GMT+0800 (CST) | D/AlarmForegroundService onCreate
4 | Fri Feb 07 2020 04:55:43 GMT+0800 (CST) | D/AlarmForegroundService startForegroundFullOs
I'm guessing this is on Android 8 (O) -- the timeout was raised to 10 seconds in Android 9 (P). Six seconds from startForegroundService() to the service actually being instantiated implies that something is inappropriately monopolizing the main looper thread. In particular, what is going on between Splash_Show and the service instance being created? That's deeply suspicious.
Re #126: "I have same problem event without explicit startForegroundService() calling, in my app I have only startService() and then if need inside service it calls startForeground(). But in some devices I see ANR with Context.startForegroundService() did not then call Service.startForeground."
This cannot happen in Android as delivered to AOSP: the "...did not then call Service.startForeground" timeout is *only* engaged in response to a call to startForegroundService(). What OEM / product / version of Android are you seeing this on?
to...@gmail.com <to...@gmail.com> #135
#134 ct....@google are there any changes made to Android 11 about that since communication have been stopped here on the internal bug.
I still have "Context.startForegroundService() did not then call Service.startForeground()" with my application not even yet started (Attached stack trace on Android 9 / Nokia 5.1)
My application should not be counted as an ANR for the system not able to properly start the application in time. For external calls, time should start from the end of the application.onCreate() return at least.
"main" prio=5 tid=1 Native | group="main" sCount=1 dsCount=0 flags=1 obj=0x74401b48 self=0x7b34014c00 | sysTid=22258 nice=0 cgrp=default sched=0/0 handle=0x7bba84b548 | state=R schedstat=( 429207992 365816403 2448 ) utm=5 stm=37 core=2 HZ=100 | stack=0x7ff4246000-0x7ff4248000 stackSize=8MB | held mutexes= #00 pc 0000000000032d04 /system/lib64/libandroidfw.so (android::ResTable_config::copyFromDtoH(android::ResTable_config const&)+12) #01 pc 0000000000024064 /system/lib64/libandroidfw.so (android::AssetManager2::RebuildFilterList()+276) #02 pc 0000000000023984 /system/lib64/libandroidfw.so (android::AssetManager2::SetApkAssets(std::__1::vector<android::ApkAssets const*, std::__1::allocator<android::ApkAssets const*>> const&, bool)+60) #03 pc 000000000012c9bc /system/lib64/libandroid_runtime.so (android::NativeSetApkAssets(_JNIEnv*, _jclass*, long, _jobjectArray*, unsigned char)+332) at android.content.res.AssetManager.nativeSetApkAssets (Native method) at android.content.res.AssetManager.access$300 (AssetManager.java:57) at android.content.res.AssetManager$Builder.build (AssetManager.java:145) at android.app.ResourcesManager.createAssetManager (ResourcesManager.java:411) at android.app.ResourcesManager.createResourcesImpl (ResourcesManager.java:490) at android.app.ResourcesManager.getOrCreateResources (ResourcesManager.java:787)
- locked <0x0d35c7d2> (a android.app.ResourcesManager) at android.app.ResourcesManager.getResources (ResourcesManager.java:853) at android.app.LoadedApk.getResources (LoadedApk.java:1029) at android.app.ContextImpl.createAppContext (ContextImpl.java:2346) at android.app.ActivityThread.handleBindApplication (ActivityThread.java:5789) at android.app.ActivityThread.access$1200 (ActivityThread.java:208) at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1680) at android.os.Handler.dispatchMessage (Handler.java:106) at android.os.Looper.loop (Looper.java:193) at android.app.ActivityThread.main (ActivityThread.java:6715) at java.lang.reflect.Method.invoke (Native method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:911)
ct...@google.com <ct...@google.com> #136
The unfortunate short answer here is that if your app takes 10 seconds to launch, that is its own problem, and needs to be addressed to make sure your app is responsive.
Also, if you're launching directly into the startForegroundService() lifecycle flow, it means you're using a foreground-service PendingIntent to do that. You have alternatives that will let you launch & pay the cost of your heavy static init prior to the startForegroundService() call: in particular, a broadcast PendingIntent trigger rather than an immediate fg service start.
to...@gmail.com <to...@gmail.com> #137
You miss read the stack trace :) My application is fast to start and overly optimised, the ANR occurs before even reaching my code or Application.onCreate() (FTR I'm under 0,01% ANR rate on Play Console)
In this case my application is publishing a stable API that is based on that service to be used from other applications and has been since more than 6 years now (the API, the app is 8), I have no willing to break all the unknown consumers because Android have decided to put timeouts on things that are out of controls of devs.
ct...@google.com <ct...@google.com> #138
to...@gmail.com <to...@gmail.com> #139
It would be funny if your mail did not ended up with @Google.com :)
I have done nothing as I said the application is highly optimized and Play Console does confirm that I'm better in all vitals than most of the Play Store. (
This is just how Android works on constrained devices that can have disk queue saturated. If you are not aware of those basics issues when reaching millions devices then maybe it's normal this issue is still not properly addressed.
ct...@google.com <ct...@google.com> #140
to...@gmail.com <to...@gmail.com> #141
It's quite rare but happens on many different low end to medium end devices. I do not see demographics in Play Console and I've stopped using firebase (And even with it AFAIK ANR are not reported) Play console only have 60 days history and any slight variation leads to another line without a way to export to consolidate the data so it's not easy and as it's 100% out of my control I did not tried to do that consolidation job.
Another kind of reasons is
"main" prio=5 tid=1 Native
| group="main" sCount=1 dsCount=0 obj=0x76d898d0 self=0x789fea1a00
| sysTid=9391 nice=0 cgrp=default sched=0/0 handle=0x78a3e82a98
| state=S schedstat=( 79785939 414062 349 ) utm=6 stm=1 core=3 HZ=100
| stack=0x7fc95fb000-0x7fc95fd000 stackSize=8MB
| held mutexes=
at java.io.UnixFileSystem.canonicalize0 (Native method)
at java.io.UnixFileSystem.canonicalize (UnixFileSystem.java:147)
at java.io.File.getCanonicalPath (File.java:586)
at java.io.File.getCanonicalFile (File.java:611)
at androidx.core.content.FileProvider.b (FileProvider.java:33)
at androidx.core.content.FileProvider.a (FileProvider.java:20)
- locked <0x0e2e93d5> (a java.util.HashMap)
at androidx.core.content.FileProvider.attachInfo (FileProvider.java:4)
at android.app.ActivityThread.installProvider (ActivityThread.java:6197)
at android.app.ActivityThread.installContentProviders (ActivityThread.java:5715)
at android.app.ActivityThread.handleBindApplication (ActivityThread.java:5636)
at android.app.ActivityThread.-wrap2 (ActivityThread.java)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1637)
at android.os.Handler.dispatchMessage (Handler.java:105)
at android.os.Looper.loop (Looper.java:156)
at android.app.ActivityThread.main (ActivityThread.java:6517)
at java.lang.reflect.Method.invoke! (Native method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:832)
did report to AndroidX but was told that if I can't reproduce on a pixel then no one cares and issue was closed. But that one is internal to the app so can be considered an app problem.
The other issue clearly is not under control and in all cases this proves that on constrained devices a very large part or all of the allowed time to call startForeground can be consumed before even reaching the application. While those timeouts sounds reasonable when calling the service from the own application process, some better handling should be done when it's from pending intents and app is not running (Widgets, other applications, ...)
ne...@gmail.com <ne...@gmail.com> #142
Let me just jump in quickly to highlight a demographic I've been seeing it on:
- 5,9 % Samsung Galaxy S10
- 3,7 % Huawei P30 Lite
- 3,7 % Samsung Galaxy S9 (starqltesq)
- 3,4 % Samsung A70
- 3,2 % Samsung Galaxy S9 (starlte)
- 2,9 % Samsung Galaxy A30
..And the rest are still mostly Samsung devices with the occasional Huawei. Definitely a trend there. Also only devices with Android 8.1 and up, none with 8. This data comes from the Play Console, where it does register as crash as well as an ANR, but the crash doesn't have a stack trace and it took me a while to figure out that it really was the same thing. Fabric/Firebase does register the crash with a stack trace that makes sense, and according to that, it's 100% high-end Samsung devices.
And btw I'm absolutely positive this issue has nothing to do with an application doing a lot of work while starting.
ct...@google.com <ct...@google.com> #143
ma...@marcardar.com <ma...@marcardar.com> #144
to...@gmail.com <to...@gmail.com> #145
Let's not mix everything, the slow resources loading is certainly not Samsung only my last reports are Nokia and Pixel 1.
I have no idea where the give numbers comes from and what they represent so let's not build theories on out of context numbers.
sl...@gmail.com <sl...@gmail.com> #146
# Crashlytics - Custom logs
# Application: com.mypackage.aio
# Platform: android
# Version: v1.1.8 (36)
# Issue: 0f763b81d15b3b03db0d4f77036de274
# Session: 5E66DF7702EB00011651253E32EBDA26_DNE_0_v2
# Date: Tue Mar 10 2020 09:43:00 GMT+0800 (中国标准时间)
0 | Tue Mar 10 2020 08:29:43 GMT+0800 (中国标准时间) | D/SplashActivity onCreate 1
1 | Tue Mar 10 2020 08:29:46 GMT+0800 (中国标准时间) | D/SplashActivity onDestroy 0
2 | Tue Mar 10 2020 08:29:50 GMT+0800 (中国标准时间) | Guide2_New_Show
3 | Tue Mar 10 2020 08:29:51 GMT+0800 (中国标准时间) | Guide3_New_Show
4 | Tue Mar 10 2020 08:29:56 GMT+0800 (中国标准时间) | Guide2_New_Show
5 | Tue Mar 10 2020 08:29:57 GMT+0800 (中国标准时间) | Guide1_New_Show
6 | Tue Mar 10 2020 08:30:41 GMT+0800 (中国标准时间) | D/SplashActivity onCreate 1
7 | Tue Mar 10 2020 08:30:42 GMT+0800 (中国标准时间) | Splash_Show
8 | Tue Mar 10 2020 08:30:42 GMT+0800 (中国标准时间) | Ad_Result_Request
9 | Tue Mar 10 2020 08:30:42 GMT+0800 (中国标准时间) | screen_view
10 | Tue Mar 10 2020 08:30:44 GMT+0800 (中国标准时间) | D/VipGuideActivity onCreate 2
11 | Tue Mar 10 2020 08:30:44 GMT+0800 (中国标准时间) | Guide_Special_Show
12 | Tue Mar 10 2020 08:30:44 GMT+0800 (中国标准时间) | screen_view
13 | Tue Mar 10 2020 08:30:44 GMT+0800 (中国标准时间) | D/SplashActivity onDestroy 1
14 | Tue Mar 10 2020 08:30:45 GMT+0800 (中国标准时间) | Guide_Special_btnSubscribe
15 | Tue Mar 10 2020 08:30:45 GMT+0800 (中国标准时间) | D/RxView onClick, deltaClickTime = 1583800246092
16 | Tue Mar 10 2020 08:30:45 GMT+0800 (中国标准时间) | screen_view
17 | Tue Mar 10 2020 08:30:48 GMT+0800 (中国标准时间) | Guide_Special_Profail
18 | Tue Mar 10 2020 08:30:48 GMT+0800 (中国标准时间) | screen_view
19 | Tue Mar 10 2020 08:30:50 GMT+0800 (中国标准时间) | D/RxView onClick, deltaClickTime = 1583800250962
20 | Tue Mar 10 2020 08:30:50 GMT+0800 (中国标准时间) | Guide_Special_btnSkip
21 | Tue Mar 10 2020 08:30:50 GMT+0800 (中国标准时间) | D/MainActivity onCreate 2
22 | Tue Mar 10 2020 08:30:50 GMT+0800 (中国标准时间) | D/SleepFragment R.drawable.sleep_drink_selector = 7f08014c
23 | Tue Mar 10 2020 08:30:50 GMT+0800 (中国标准时间) | screen_view
24 | Tue Mar 10 2020 08:30:50 GMT+0800 (中国标准时间) | D/VolumeSampleDbHelper get
25 | Tue Mar 10 2020 08:30:50 GMT+0800 (中国标准时间) | Sleep_Show
26 | Tue Mar 10 2020 08:30:51 GMT+0800 (中国标准时间) | screen_view
27 | Tue Mar 10 2020 08:30:51 GMT+0800 (中国标准时间) | D/VipGuideActivity onDestroy 1
28 | Tue Mar 10 2020 08:30:55 GMT+0800 (中国标准时间) | screen_view
29 | Tue Mar 10 2020 08:30:58 GMT+0800 (中国标准时间) | Records_noData_Show
30 | Tue Mar 10 2020 08:30:58 GMT+0800 (中国标准时间) | Ad_Records_Request
31 | Tue Mar 10 2020 08:30:58 GMT+0800 (中国标准时间) | Records_Show
32 | Tue Mar 10 2020 08:30:59 GMT+0800 (中国标准时间) | More_Show
33 | Tue Mar 10 2020 08:31:00 GMT+0800 (中国标准时间) | Sleep_Show
34 | Tue Mar 10 2020 08:31:01 GMT+0800 (中国标准时间) | Sleep_btnAlcohol
35 | Tue Mar 10 2020 08:31:02 GMT+0800 (中国标准时间) | Sleep_btnAlcohol
36 | Tue Mar 10 2020 08:31:02 GMT+0800 (中国标准时间) | Sleep_btnAteLate
37 | Tue Mar 10 2020 08:31:03 GMT+0800 (中国标准时间) | Sleep_btnAteLate
38 | Tue Mar 10 2020 08:31:05 GMT+0800 (中国标准时间) | Sleep_btnCaffeine
39 | Tue Mar 10 2020 08:31:05 GMT+0800 (中国标准时间) | Sleep_btnCaffeine
40 | Tue Mar 10 2020 08:31:06 GMT+0800 (中国标准时间) | D/RxView onClick, deltaClickTime = 1583800266779
41 | Tue Mar 10 2020 08:31:06 GMT+0800 (中国标准时间) | Sleep_btnStartSleep
42 | Tue Mar 10 2020 08:31:06 GMT+0800 (中国标准时间) | Ad_Result_Request
43 | Tue Mar 10 2020 08:31:06 GMT+0800 (中国标准时间) | Sleep_Guide3_Show
44 | Tue Mar 10 2020 08:31:06 GMT+0800 (中国标准时间) | screen_view
45 | Tue Mar 10 2020 08:31:10 GMT+0800 (中国标准时间) | Ad_Records_Request
46 | Tue Mar 10 2020 08:31:10 GMT+0800 (中国标准时间) | screen_view
47 | Tue Mar 10 2020 08:31:10 GMT+0800 (中国标准时间) | D/SleepingActivity onCreate 2
48 | Tue Mar 10 2020 08:31:10 GMT+0800 (中国标准时间) | D/ContextUtil startForegroundService, com.mypackage.control.SleepSamplingService
49 | Tue Mar 10 2020 08:31:10 GMT+0800 (中国标准时间) | Sleep_AccelGuide_Show
50 | Tue Mar 10 2020 08:31:10 GMT+0800 (中国标准时间) | D/SleepSamplingService onCreate
51 | Tue Mar 10 2020 08:31:10 GMT+0800 (中国标准时间) | screen_view
52 | Tue Mar 10 2020 08:31:10 GMT+0800 (中国标准时间) | D/SleepSamplingService startForegroundFullOs
53 | Tue Mar 10 2020 08:31:10 GMT+0800 (中国标准时间) | D/SleepSamplingService startForegroundFullOs
54 | Tue Mar 10 2020 08:31:10 GMT+0800 (中国标准时间) | D/SleepingActivity onKeyDown keyCode=4
55 | Tue Mar 10 2020 08:31:10 GMT+0800 (中国标准时间) | D/SleepSamplingService onDestroy
56 | Tue Mar 10 2020 08:31:10 GMT+0800 (中国标准时间) | D/Mp3DbHelper get
57 | Tue Mar 10 2020 08:31:10 GMT+0800 (中国标准时间) | Ad_Records_Request
58 | Tue Mar 10 2020 08:31:10 GMT+0800 (中国标准时间) | screen_view
59 | Tue Mar 10 2020 08:31:11 GMT+0800 (中国标准时间) | D/SleepingActivity onDestroy 1
ne...@gmail.com <ne...@gmail.com> #147
"Let's not mix everything, the slow resources loading is certainly not Samsung only my last reports are Nokia and Pixel 1.
I have no idea where the give numbers comes from and what they represent so let's not build theories on out of context numbers."
Will all due respect: lol.
The provided numbers come from the Google Play console. Should be quite the reliable source. They are most definitely not out of context and this "theory" is very much proven. Slow resources loading is unrelated (could have a similar effect but I highly doubt that's what most people experience), this most definitely is a bug that happens almost exclusively on Samsung devices.
to...@gmail.com <to...@gmail.com> #148
So you confirm that your numbers are 100% unrelated to the sub discussion that was occurring? I talked about that loading ressources issues, he ask ME the demographics about them and you jumped in with now confirmed unrelated numbers without telling about what they where related :)
So thanks for the actual lol ;) There's a dozens reasons why this ANR can occurs, you do not give the full stack trace about the possible reason that is maybe something you do on that cause a problem on Samsung, I do not have this issue on Samsung and I have more than 500 000 MAU. So give the full stack trace for a common ANR cause that occurs only on Samsung and maybe there will be some valuable info for you ;)
ne...@gmail.com <ne...@gmail.com> #149
Wow okay, I actually did not notice you are the same person as the one who was sharing the stack traces and explaining how their app does NOT take more than five seconds to prepare. Or did I misunderstand that? Because now it sounds like you're arguing with yourself and that's just really confusing.
Anyway, I said "Let me just jump in quickly to highlight a demographic I've been seeing it on", "it" being the issue at hand in general, not necessarily related to resources. Where it would appear we were in agreement before that this issue just happens, regardless of resources loading. That's what was being explained, wasn't it?
Also I believe I did provide a stack trace quite some time ago, and if I didn't, it might be because it looks exactly the same as all the stack traces given here before. There is no new valuable information available. Btw congrats on your 500k, I have 200k with dozens to low hundreds of these ANRs every day (or crashes, I honestly don't know what really happens on the device other what Firebase/Google Play gives me, which is two different information that share the same numbers) and they rarely happen on anything other than Samsung. Though the Huawei there sure is interesting, and I've seen some Nokias too I believe, which would suggest that the problem is in fact not completely Samsung's fault, which is why it's a thread here, isn't it. But I still believe that the fact that Samsung is the main culprit can help with solving this issue and should not be discarded, which is what I felt your earlier comment suggested.
to...@gmail.com <to...@gmail.com> #150
This is a conversation, so order of things matters, I report a specific case about resources, the guy ask for demographic for that specific issue, I said I have not you jump, in saying here's demographics, so in an normal world this means you are referring to the actual running conversation :)
You have never posted in this thread with any stack trace or ANR dump, and actually no one have posted a full ANR report except me, just pasting the error
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Is not a full stack trace / ANR dumps with all the running threads and what is really happening.
So again, no there's no generic Samsung issue as Samsung is as many others my most active devices and I do extensively rely on startForeground.
Provide a proper ANR trace with all threads and I'll assure you there's plenty of different reasons for the crash / ANR. How the system report the crash via sending a message is the same and that's what that small logcat extract shows. This is not the cause this is the consequence.
TL;DR an ANR dump and a logcat error log are very different and without the proper ANR dumps your numbers represent absolutely nothing. Yes there's Samsung issues that can be workarounded with media session for example. So if you play with those on main thread during that call you can trigger this ANR, but this is not something Google can fix, it's Samsung bug and there's workarounds. So provide the full ANR dumps and I'm pretty sure I'll have some history about them and workarounds.
For the record a screenshot of the Vitals for that app, as you can see there's no ANR lines because I managed to remove nearly all of them and the remaining are like the one I posted here.
ne...@gmail.com <ne...@gmail.com> #151
Well then I misunderstood the question (and it really wasn't that clear as to what demographic they mean, or if they mean to be specific), so to clarify, I have provided what I believe to be the demographic for the general error. To add to my claims, I'm sure I'm not the first to mention it's mostly Samsung here or in other threads. Yet again you are discarding that information as irrelevant. I'm simply saying there is a probable connection.
"Yes there's Samsung issues that can be workarounded with media session for example." - please elaborate, I have zero idea what you mean by this.
So what exactly is an ANR dump and how do I provide it? Where do I get one? Naturally that stack trace you mention is useless, which is what I said as well. But the only information I have is what Google Play Console tells me and I don't see a way to export that or if it even is what you're asking for. To me, it looks like it doesn't really hold a lot of information either.
to...@gmail.com <to...@gmail.com> #152
See attached images :) Not very hidden.
And I'm not dismissing what you say about Samsung just that it's irrelevant information without the ANR dump. You are probably doing something that trigger an issue on Samsung, but this is not a general issue on Samsung that everybody face as proven.
un...@gmail.com <un...@gmail.com> #153
I found this thread super useful. I also saw that it was especially common on Samsung devices out in the field. And I think it has allowed me to construct a workaround that completely hides this problem. I'm posting it here in case it is useful for my sister/brother android devs ;-).
I think for many usecases people are calling startForegroundService in a BOOT_COMPLETE receiver (in my case so I can start talking to a bluetooth device). Unfortunately that first 30 seconds or so of an Android boot is a very busy time - with lots of threads starting and running. It is completely plausible that if you try to start your service that early , your service will start running and then end up blocked for a long time (because of some thread outside of your control) and you'll hit that dreaded timeout.
My workaround is to use the new WorkManager to push my service start later - about 1 minute later. After the phone isn't so hot with everyone else starting up. Here's the code I used:
ph...@gmail.com <ph...@gmail.com> #154
ne...@gmail.com <ne...@gmail.com> #155
That is not true, my services have always ran on a different process and the issue still remains.
kl...@gmail.com <kl...@gmail.com> #156
mi...@gmail.com <mi...@gmail.com> #157
I am facing this issue in my app since 1 year. I tried a lot of solutions to solve this problem. But only 1 solution that actually worked and was my mistake is:
1) After starting service in onCreate i was calling stopSelf() before calling startForeground() of service. Make sure you don't do this. It mostly happens when your app run in service completely and you have given a button to user to turn off and on so in actual it's service that starts and stops. So make sure after turn on you put some delay before you turn it off maybe delay on button clicks.
But this solution didn't solved all the crashes and i am still getting these crashes mostly on Samsung and Huawei devices with android version 8.1 only.
Now i read a
Thanks
ht...@gmail.com <ht...@gmail.com> #158
none of the suggestions worked for us - we still got a lot of exceptions logged in Play console vitals (though lower number with all the suggestions applied). I guess, even if the app does everything right, sometimes device may be in state when it struggles to process everything in time and you get more than 5s between startForegroundService and service.startForeground calls.
What's worked for us was a complete startForegroundService call removal from the project. Instead, context.bindService + startService + service.startForeground approach is now used and that finally resolved the issue (you can do that combination where you previously did startForegroundService).
Thanks!
wa...@gmail.com <wa...@gmail.com> #159
ma...@gmail.com <ma...@gmail.com> #160
mi...@gmail.com <mi...@gmail.com> #161
Tried a lot of stuff inspired by this thread and stackoverflow thread. Still getting this ANR a lot.
ai...@gmail.com <ai...@gmail.com> #162
Suggestion from
ey...@gmail.com <ey...@gmail.com> #163
ey...@gmail.com <ey...@gmail.com> #164
ma...@gmail.com <ma...@gmail.com> #165
lu...@gmail.com <lu...@gmail.com> #166
1. startService in the onStart of Main Activity, so we can keep the service running. If don't call it, after the activity stopped, the service is unbinded, it will be killed even if it is set as foreground service.
I start the service in onStart not onCreate, because the service may be destroyed, then the saving service instance in Acivity will be invalid. Such as there is a quit action in the notification, the service can be killed by the action and the activity is still paused. Users may resume the activity than re-create the App.
2. bindService following the startService in the onStart, so can get an instance of service.
3. Unbind the service in the onStop of Main activity.
4. write a function in the service which calls Service::startForeground, use the service instance which get from the binded in the activity to replace the Context.startForegroundService
I think the Context.startService should offer a ServiceConnection param as optional, so apps can pass it to get the service instance directly. the bindService with create flag can not meet all requirements. the service instance from BindService will be lost in some cases.
pv...@swooby.com <pv...@swooby.com> #167
Sad that 3.5 years and 197 stars later this "closed won't fix, intended" issue that Google essentially created in a vacuum for no valid reason still affects devs and their users that Google refuses to acknowledge and fix.
But that still may not help code where it is not possible to bind to the [especially to a legacy/unbindable 3rd party] service.
Good luck out there fellow coders!
49...@qq.com <49...@qq.com> #168
a....@mastertraining.it <a....@mastertraining.it> #169
mu...@gmail.com <mu...@gmail.com> #170
I am facing same issue. kindly guide me thanks in advance.
Context.startForegroundService() did not then call Service.startForeground
ch...@gmail.com <ch...@gmail.com> #171
Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{7996535
en...@gmail.com <en...@gmail.com> #173
kr...@gmail.com <kr...@gmail.com> #174
ku...@gmail.com <ku...@gmail.com> #175
[Deleted User] <[Deleted User]> #176
he...@gmail.com <he...@gmail.com> #177
me...@gmail.com <me...@gmail.com> #179
sa...@pocketfm.com <sa...@pocketfm.com> #180
gu...@gmail.com <gu...@gmail.com> #181
1) Started the service as background service and after binding the service we are marking service as foreground by calling startForeground
2) added a delay while stopping the service so that service can be marked to foreground before stopping itself.
3) Calling startForegroundService from handler and posting it on main looper
nothing worked, can we please check the root cause of this issue ?
mh...@gmail.com <mh...@gmail.com> #182
I read all comment and didn't find any proper solution till now. In my case this issue is only occurring on android 11 devices only and most of them are Samsung devices. I have 10 users and 500 events in just 5 days (App: Music Player) on google play console If Any one find solution then let me know. Thank you in advance...
pv...@swooby.com <pv...@swooby.com> #183
re...@gmail.com <re...@gmail.com> #184
This issue is OLD and it's still not fixed?!
I have tried several work-arounds including those mentioned in this thread but none of them worked. Even ContextCompat.startForegroundService()
crashes on some Android versions.
What did work for me is to, first, attempt to start the service as a background service, then, if that fails, start it as a foreground service:
fun startService(context: Context) {
val intent = Intent(context, MyService::class.java)
// Try to start it as a background service first.
val started = try {
context.startService(intent)
true
} catch (e: Throwable) {
e.printStackTrace()
false
}
// If that fails, try to start it as a foreground service.
if (!started) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
}
} catch (e: Throwable) {
e.printStackTrace()
}
}
}
Then, in MyService
's onStartCommand()
and onCreate()
methods, I elevate the service to foreground by calling startForeground()
, passing the needed notification.
override fun onCreate() {
super.onCreate()
startForeground(NOTIFICATION_ID, myNotification)
// ...
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
startForeground(NOTIFICATION_ID, myNotification)
// ...
return super.onStartCommand(intent, flags, startId)
}
I've tested this on Android 9, 10 and 12 and so far, hadn't had an issue yet. But then again, I only have these 3 devices.
he...@gmail.com <he...@gmail.com> #185
bi...@gmail.com <bi...@gmail.com> #186
li...@gmail.com <li...@gmail.com> #187
zi...@gmail.com <zi...@gmail.com> #188
06-08 11:44:59.105 [I] 3699 [null] 1 [main] [AAAAAService]: onStartCommand
06-08 11:44:59.237 [I] 3699 [null] 1 [main] [AAAAAService]: onDestroy
06-08 11:45:05.428 [E] 3699 [null] 1 [main] [Crash]: android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
mu...@gmail.com <mu...@gmail.com> #189
here's the different
- stopService(intent): This method is used to stop a service that was started using the startService(intent) method. It stops the service regardless of whether it was started as a foreground service or a background service. When you call stopService(intent), the service's onDestroy() method will be called, allowing you to perform any necessary cleanup or resource release.
- stopForegroundService(notifid): This method is specifically used to stop a foreground service that was started using the startForeground(id, notification) method. A foreground service is a type of service that displays a persistent notification to the user, indicating that the service is running. By calling stopForegroundService(notifid), you are telling the system to remove the service's foreground status and notification. However, the service itself will continue to run in the background unless you also call stopSelf() or stopService(intent).
pa...@outlook.com <pa...@outlook.com> #190
It's pathetic how Android just takes a dump on major issues like these and leaves us hanging with their utter incompetence.
re...@gmail.com <re...@gmail.com> #191
Is there any update? Plan to address this issue?
he...@gmail.com <he...@gmail.com> #192
use this method ,can ignore 5s limit
Description
STEPS:
1) call Context.startForegroundService(...)
2) before Service.startForeground(...) is called, call Context.stopService(...)
EXPECTED:
App doesn't crash
ACTUAL:
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
-Android build
OPM1.171019.021
-Please provide sample project or apk to reproduce the issue.
NOTE: Use of postDelayed is intentional to repro bug
-Logcat output
03-21 16:03:44.647 5385-5385/com.github.paulpv.foregroundserviceapi26 D/MainService: +onCreate()
03-21 16:03:44.647 5385-5385/com.github.paulpv.foregroundserviceapi26 D/MainService: -onCreate()
03-21 16:03:44.648 5385-5385/com.github.paulpv.foregroundserviceapi26 D/MainService: +onStartCommand(...)
03-21 16:03:44.651 5385-5385/com.github.paulpv.foregroundserviceapi26 D/MainService: -onStartCommand(...)
03-21 16:03:45.127 5385-5385/com.github.paulpv.foregroundserviceapi26 D/MainService: +onDestroy()
03-21 16:03:45.128 5385-5385/com.github.paulpv.foregroundserviceapi26 D/MainService: -onDestroy()
03-21 16:03:45.129 5385-5385/com.github.paulpv.foregroundserviceapi26 D/AndroidRuntime: Shutting down VM
03-21 16:03:45.132 5385-5385/com.github.paulpv.foregroundserviceapi26 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.github.paulpv.foregroundserviceapi26, PID: 5385
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
-Android bug report
Attached