On our application there's a service that is normally started during Application.OnCreate (directly calling context.startService) and also later on via AlarmManager (refactor is in progress to migrate some of its work to JobScheduler).
Our application also have a BroadcastReceiver that gets launched with its direct intent.
Given the new limitations in Android Oreo (https://developer.android.com/about/versions/oreo/android-8.0-changes.html) we're having an issue as follows:
app/process is in background/dead
BroadcastReceiver gets fired by the OS
Application.onCreate() executes before the BroadcastReceiver
Application.onCreate() code tries to run the Service
this leads to crash with "IllegalStateException: Not allowed to start service Intent".
I'm aware of the new recommended ways of launching a Service as answered by CommonsWare here https://stackoverflow.com/a/44505719/906362, but for this specific case, I simply want to have if(process in foreground) { startService }. I'm currently using the following method and it seems to work:
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static boolean isProcessInForeground_V21(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.AppTask> tasks = am.getAppTasks();
return tasks.size() > 0;
}
But I can't find the exact checks Android Oreo is doing (I got as far as here https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/ContextImpl.java on the startServiceCommon method, but from there requireForeground flag seems to go to some native implementation)
So my question:
For the specific purpose of Android Oreo new limitations, how to check if my process is foreground before calling startService?
To continue your investigation: (TL;DR: see between horizontal lines at the bottom)
Disclaimer, I don't know too much about Android, I just like digging in the source code.
Note: you can also navigate the code in Android Studio if you jump to file instead of class:
or searching for text in Project and Libraries.
IActivityManager is defined by AIDL, that's why there are no sources for it:
https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/app/IActivityManager.aidl#145
Based on how AIDL needs to be implemented I found that ActivityManagerService extends IActivityManager.Stub (God bless Google indexing).
Note I also found this, which might be an interesting read if you're really interested how things work internally.
https://programmer.group/android-9.0-source-app-startup-process.html
ActivityManagerService sources reveal that in Oreo startService is forwarded to ActiveServices which is located in the same package.
Assuming we're looking for an exception like this:
java.lang.IllegalStateException: Not allowed to start service Intent {...}: app is in background uid UidRecord{af72e61 u0a229 CAC bg:+3m52s273ms idle procs:1 seq(0,0,0)}
we have to continue down the rabbit hole: requireForeground gets assigned to fgRequired parameter and the message is here. The condition to allow this depends on the start mode returned by ActivityManagerService.getAppStartModeLocked(packageTargetSdk = 26 or greater, disabledOnly = false, forcedStandby = false).
There are 4 start modes:
APP_START_MODE_NORMAL (needs to be different than this, i.e. !=)
APP_START_MODE_DELAYED (this is ok, i.e. return null)
APP_START_MODE_DELAYED_RIGID
APP_START_MODE_DISABLED
Ephemeral apps will immediately return APP_START_MODE_DISABLED, but assuming this is a normal app, we end up in appServicesRestrictedInBackgroundLocked.
Note: this is where some of the whitelist mentioned in https://stackoverflow.com/a/46445436/253468 is decided.
Since all branches but last return APP_START_MODE_NORMAL, this redirects to appRestrictedInBackgroundLocked where we find our most likely suspect:
int appRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk) {
// Apps that target O+ are always subject to background check
if (packageTargetSdk >= Build.VERSION_CODES.O) {
return ActivityManager.APP_START_MODE_DELAYED_RIGID;
}
So the reason for denial is simply targeting O. I think the final answer to your question of how the OS decides if your app is foreground or background is this condition in getAppStartModeLocked
UidRecord uidRec = mActiveUids.get(uid);
if (uidRec == null || alwaysRestrict || uidRec.idle) {
My guess is that a missing record means it's not running (but then how is it starting a service?!), and idle means it's backgrounded. Notice that in my exception message the UidRecord is saying that it's idle and has been backgrounded for 3m52s.
I peeked into your getAppTasks and it's based on TaskRecord.effectiveUid, so I'm guessing that's quite close to listing UidRecords for your app.
Not sure if this helps, but I'll post it anyway, so if anyone wants to investigate more, they have more info.
When I try to launch my AndEngine Activity, I get this error:
ERROR/InputDispatcher(21374): channel '4122e148 my.package.AcGame (server)' ~ Channel is unrecoverably broken and will be disposed!
The app doesn't crash, but there's a black screen and the device doesn't react to pressing the 'back' or 'home' buttons.
Does anyone know what the problem is?
One of the most common reasons I see that error is when I am trying to display an alert dialog or progress dialog in an activity that is not in the foreground. Like when a background thread that displays a dialog box is running in a paused activity.
I think that You have memory leaks somewhere. You can find tips to avoid leaking memory here. Also you can learn about tools to track it down here.
Have you used another UI thread? You shouldn't use more than 1 UI thread and make it look like a sandwich. Doing this will cause memory leaks.
I have solved a similar issue 2 days ago...
To keep things short: The main thread can have many UI threads to do multiple works, but if one sub-thread containing a UI thread is inside it, The UI thread may not have finished its work yet while it's parent thread has already finished its work, this causes memory leaks.
For example...for Fragment & UI application...this will cause memory leaks.
getActivity().runOnUiThread(new Runnable(){
public void run() {//No.1
ShowDataScreen();
getActivity().runOnUiThread(new Runnable(){
public void run() {//No.2
Toast.makeText(getActivity(), "This is error way",Toast.LENGTH_SHORT).show();
}});// end of No.2 UI new thread
}});// end of No.1 UI new thread
My solution is rearrange as below:
getActivity().runOnUiThread(new Runnable(){
public void run() {//No.1
ShowDataScreen();
}});// end of No.1 UI new thread
getActivity().runOnUiThread(new Runnable(){
public void run() {//No.2
Toast.makeText(getActivity(), "This is correct way",Toast.LENGTH_SHORT).show();
}});// end of No.2 UI new thread
for you reference.
I am Taiwanese, I am glad to answer here once more.
You can see the source code about this output here:
void InputDispatcher::onDispatchCycleBrokenLocked(
nsecs_t currentTime, const sp<Connection>& connection) {
ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
connection->getInputChannelName());
CommandEntry* commandEntry = postCommandLocked(
& InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
commandEntry->connection = connection;
}
It's cause by cycle broken locked...
I got similar error (my app crashes) after I renamed something in strings.xml and forgot to modify other files (a preference xml resource file and java code).
IDE (android studio) didn't showed any errors. But, after I repaired my xml files and java code, app ran okay. So, maybe there are some small mistakes in your xml files or constants.
I had the same problem.
To solve the error:
Close it on the emulator and then run it using Android Studio.
The error happens when you try to re-run the app when the app is already running on the emulator.
Basically the error says - "I don't have the existing channel anymore and disposing the already established connection" as you have run the app from Android Studio again.
I had the same problem but mine was Due To an Android database memory leak. I skipped a cursor. So the device crashes so as to fix that memory leak. If you are working with the Android database check if you skipped a cursor while retrieving from the database
I had the same problem. Mine was due to a third jar, but the logcat did not catch the exception, i solved by update the third jar, hope these will help.
As I faced this error, somewhere in your code your funcs or libraries that used run on different threads, so try to call all code on the same thread , it fixed my problem.
If you call methods on WebView from any thread other than your app's UI thread, it can cause unexpected results. For example, if your app uses multiple threads, you can use the runOnUiThread() method to ensure your code executes on the UI thread:
Google reference link
It's obvious this creeps up due to many issues.
For me, I was posting several OneTimeWorkRequest, each accessing a single room database, and inserting into a single table.
Making the DAO functions suspended, and calling them within the coroutine scope of the worker fixed this for me.
It happened for me as well while running a game using and-engine.
It was fixed after i added the below code to my manifest.xml. This code should be added to your mainactivity.
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|mcc|mnc"
Reading through all contributions, it looks like many different origins exhibit cause this same problem symptoms.
In my case for instance - I got this problem as soon as I added
android:progressBackgroundTintMode="src_over"
to my progress bar properties.
I think the GUI designer of ADT is known for several bugs. Hence I assume this is one of them. So if you encounter similar problem symptoms (that just do not make sense) after playing with your GUI setup, just try to roll back what you did and undo your last GUI modifications.
Just press Ctrl+z with the recently modified file on screen.
Or:
The Version Control tool could be helpful. Open the Version Control panel - choose Local Changes tab and see recently modified (perhaps .xml) files.
Right click some most suspicious one and click Show Diff.
Then just guess which modified line could be responsible.
Good luck :)
I was having the same problem too. In my case was caused when trying to reproduce videos with a poor codification (demanded too much memory).
This helped me to catch the error and request another version of the same video.
https://stackoverflow.com/a/11986400/2508527
In my case these two issue occurs in some cases like when I am trying to display the progress dialog in an activity that is not in the foreground. So, I dismiss the progress dialog in onPause of the activity lifecycle. And the issue is resolved.
Cannot start this animator on a detached view! reveal effect BUG
ANSWER: Cannot start this animator on a detached view! reveal effect
Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!
ANSWER: Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'
#Override
protected void onPause() {
super.onPause();
dismissProgressDialog();
}
private void dismissProgressDialog() {
if(progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
}
I had this issue and the cause was actually a NullPointerException. But it was not presented to me as one!
my Output:
screen was stuck for a very long period and ANR
My State :
the layout xml file was included another layout, but referenced the included view without giving id in the attached layout. (i had two more similar implementations of the same child view, so the resource id was created with the given name)
Note : it was a Custom Dialog layout, so checking dialogs first may help a bit
Conclusion :
There is some memory leak happened on searching the id of the child view.
This error occurred in case of memory leak. For example if you have any static context of an Android component (Activity/service/etc) and its gets killed by system.
Example: Music player controls in notification area. Use a foreground service and set actions in the notification channel via PendingIntent like below.
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(AppConstants.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Intent previousIntent = new Intent(this, ForegroundService.class);
previousIntent.setAction(AppConstants.ACTION.PREV_ACTION);
PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
previousIntent, 0);
Intent playIntent = new Intent(this, ForegroundService.class);
playIntent.setAction(AppConstants.ACTION.PLAY_ACTION);
PendingIntent pplayIntent = PendingIntent.getService(this, 0,
playIntent, 0);
Intent nextIntent = new Intent(this, ForegroundService.class);
nextIntent.setAction(AppConstants.ACTION.NEXT_ACTION);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder
.setOngoing(true)
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setContentTitle("Foreground Service")
.setContentText("Foreground Service Running")
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setPriority(NotificationManager.IMPORTANCE_MAX)
.setCategory(Notification.CATEGORY_SERVICE)
.setTicker("Hearty365")
.build();
startForeground(AppConstants.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
And if this notification channel get broken abruptly (may be by system, like in Xiomi devices when we clean out the background apps), then due to memory leaks this error is thrown by system.
For me it was caused by a splash screen image that was too big (over 4000x2000). The problem disappeared after reducing its dimensions.
Just Try to Invalidate the IDE cached and restart. This wont fix the issue. But in my case doing this revealed the possible crash
Please check you Realm entity class.
If you declare variable as lateinit var and
you try to check that uninitialized variable check with isNullOrEmpty() return "Channel is unrecoverably broken and will be disposed!"
In my case I was setting value in background thread viewModelScope.launch(Dispatchers.IO) { } so app was crashing solution in my case I was removed (Dispatchers.IO). viewModelScope.launch{ }
In my case, I was using Glide library and the image passed to it was null. So it was throwing this error. I put a check like this:
if (imageData != null) {
// add value in View here
}
And it worked fine. Hope this helps someone.
I got same logcat message, just realize that string.xml value of array cannot be number/digit, but only text/alphabet is allowed.
In my case
this error is happening because of not connected to firebase firestore but using the same.
To rectify the issue please go to Tools-> Firebase
when a window will open on RHS choose the options to
-> Connect your app to Firebase
-> Add Cloud Firestore to your app
Check your ViewModel class and not finding any issue then try to comment code where you using launch or withContext.
In my case, I commented on code where I am using launch or withContext and it worked my app is running normally.
I had a kind of issue you described. In my case it happened only in release builds. It was caused by the obfuscation: native methods crashed silently on FindClass or GetMethodID call cuz the names were obfuscated. Editing proguard-rules worked out!
The issue for me was I havent defined the instance of an Activity.
Eg:
Myclass my;
onCreate() {
my.getData();
}
Instead of:
Myclass my;
onCreate() {
my = new Myclass();
my.getData();
}
This is weird as Studio has to give some good defining error message.
Just to add to many other answers:
My app crashed without anything relevant in LogCat. My Retrofit network call that caused the crash looked like this:
CoroutineScope(Dispatchers.IO).launch {
val response = api.getData()
}
and used the following method signature
suspend fun getData() : Response<RatesResponse>
I changed it removing Response from the return type & got it working 🤷
suspend fun getData() : RatesResponse
There are two ways this can be resolved,
Try removing the Dispatchers.XXX from the launch
viewModelScope.launch(Dispatchers.IO) { }
viewModelScope.launch{ }
Add CoroutineExceptionHandler to catch the exception, this will tell you what exactly is going wrong.
val handler = CoroutineExceptionHandler { coroutineContext, throwable ->
Log.d("TAG","EROR ${throwable.message}")
}
lifecycleScope.launch(handler) { }
When it happened to me:
Forgot to delete TODO().
SQL query result with a null field getting assigned to a non null data class's field.
I'm trying to put a device into sleep mode for a certain amount of time, say x, by calling..
powerManager.goToSleep(xNumberOfMilliseconds);
However, the api never seems to work consistently, and never for any amount of time greater than 1000 milliseconds. I'm stumped. I have the appropriate permissions, my application has its sharedUserId set to "android.uid.system" in the manifest, and the application is signed with the same key the firmware itself is signed with (platform key).
It is a pretty simple API call, so I don't really know what on earth is going wrong. I've been able to get this problem on both a device running android 2.3 and a device running android 3.2.
Any ideas?
I have done this but it works at random on several android 4.0.x plaforms.
powerManager.goToSleep(SystemClock.uptimeMillis() + timeMs)
Did anyone managed to use the method the way he has intended to?
Edit:
It seems the right answer was what figure in the code below:
public void sleepFor(long time, Context context) {
//Create a new PendingIntent, to wake-up at the specified time, and add it to the AlarmManager
Intent intent = new Intent(context, this.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent wakeupIntent = PendingIntent.getActivity(context, CODE_WAKE_UP_DEVICE, intent, PendingIntent.FLAG_CANCEL_CURRENT);
// CODE_WAKE_UP_DEVICE is a dummy request code.
AlarmManager am = getAlarmManager();
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + time, wakeupIntent);
powerService.goToSleep(SystemClock.uptimeMillis() + 1);
}
ContentResolver cr= getContentResolver();
android.provider.Settings.System.putInt(cr,android.provider.Settings.System.SCREEN_OFF_TIMEOUT
,1000);
According to the documentation, current system time would be more appropriate parameter for goToSleep() than the desired sleep duration:
powerManager.goToSleep(SystemClock.uptimeMillis())
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Intent to launch the clock application on android
I have a widget that displays the time and if one taps on it, it launches the com.android.alarmclock/.AlarmClock activity with an PendingIntent. This works great before-Froyo, but with Froyo, I have to launch the com.android.deskclock/.AlarmClock. So I want to put in code that checks for the class existence and launch the appropriate activity/intent. Here is what I tried, but it does not work.
Intent alarmIntent = new Intent();
try {
if (Class.forName("com.android.deskclock.AlarmClock") != null) {
Log.i(TAG, "setting deskclock alarm -- must be Froyo!");
alarmIntent.setClassName("com.android.deskclock",
"com.android.deskclock.AlarmClock");
}
} catch (ClassNotFoundException e) {
Log.i(TAG, "setting alarmclock alarm -- must be Eclair!");
alarmIntent.setClassName("com.android.alarmclock",
"com.android.alarmclock.AlarmClock");
}
PendingIntent pendingIntent = PendingIntent.getActivity(context, REQUEST_UPDATE_TIME_NOW,
alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.text_timeofday, pendingIntent);
It always thinks it is "Eclair" and therefore fails on Froyo. Is this the best approach, or should I check the application-level? I prefer to work with the class existence.
if (Class.forName("com.android.deskclock.AlarmClock") != null)
That won't work, because that class is not in your project. At most, it might be in some other project on the device.
There is no documented supported Intent for launching an alarm clock in the Android SDK. Your approach of hard-wiring in package and class names is fragile, as you're discovering. It won't work on some devices, if they do not have that application (e.g., replaced by one from the device manufacturer). Plus, as you've seen, it may change in future versions of Android. I am having a rough enough time trying to convince device manufacturers not to break the SDK; having third-party developers do it weakens my case.
That being said, the general way to see if something will respond to an Intent is to use PackageManager (e.g., queryIntentActivities()).