I do have an old app that refuses to work on Android 4.1 devices. It's the NetworkOnMainThreadException that jumps in here.
So I tried to permit this with the following steps - but these don't work. I tested that with the 4.1 emulator. What is really needed to come around that error - app rewrite is no option. Currently I exclude 4.1 devices from my apps.
A class file ...
public class StrictModeWrapper {
static {
try {
Class.forName("android.os.StrictMode");
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
public static void checkAvailable() {
}
#SuppressLint("NewApi")
public static void setThreadPolicy() {
StrictMode.ThreadPolicy strictModeThreadPolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(strictModeThreadPolicy);
}
}
... called in an extended Application class:
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
try {
StrictModeWrapper.checkAvailable();
StrictModeWrapper.setThreadPolicy();
} catch (Throwable throwable) {
}
}
}
The extended Application class is registered in the Manifest and working.
Nothing seems to have changed in StrictMode since api 11. It must be the changes in some other android classes you used, that caused a StrictMode policy violation.
The Android documentation itself says
"But don't feel compelled to fix everything that StrictMode finds. "
But since its a NetworkOnMainThreadException you must do a thorough check. See all network communications in your app, and ensure that they are not blocking your main thread.
And make sure you remove/disable the StrictMode code in your release build, as it is only a developer tool to identify accidental mistakes.
Update:
Your app crashed because :
You had not blocked the execution of StrictMode policy setting code in your release build. It should be executed only while testing.
Something changed in the StrictMode class that caused the strict mode policy to reset after onCreate.
I have 2 questions :
Doesnt the crash indicate that the StrictMode policy was working? There was a policy violation and hence it crashed.
Doesnt it indicate that there is some network code in your app that blocks the main thread?
StrictMode behaves different on Android version >= 16 than prior releases. The docs suggest to issue StrictMode calls in onCreate() of an extended Application, Activity, etc.. At least onCreate() in an extended Application works different now and proofes the docs wrong (as of today).
Here's the StrictMode doc that describes how to add StrictMode calls to an extended application for example (that's wrong as of today):
StrictMode
Here's a Google Code issue that describes the problem and gives a workaround:
Google Code Issue 35298
Related
Currently trying to obtain profile trace logs files for a huge Android app, that we have instrumented on MyApplication class, following the documentation about instrumenting my app to get trace logs.
We are trying to dig into what happens when our app is initialized and Dagger2 creates the object graph when the app is started.
A cold startup can take a few seconds normally, the issue I have is that when I add the Debug traces, it dramatically slows down the initialization of the app, making it crash with an ANR message.
com.github.anrwatchdog.ANRError: Application Not Responding
Caused by: com.github.anrwatchdog.ANRError$$$_Thread: main (state = RUNNABLE)
I would like to know if there is a way to prevent the Android OS from crashing my app when it blocks for a long period of time, or to at least increase the ANR threshold.
Any help or tips are welcome. Thanks!
For further context, this is roughly what I am doing in my MyApplication.class:
public void onCreate() {
super.onCreate();
Debug.startMethodTracing("MyApp_onCreate()");
injectSelf();
AppInit.initApp(this);
Debug.stopMethodTracing();
}
Actually, it turns out we have our own ANRWatchDogManager which I wasn't aware of, where I can extend the limit.
public class ANRWatchDogManager implements ANRWatchDog.ANRListener {
Somewhere in that class:
public void startANRWatchDog() {
final int timeoutInterval = isDebugBuild() && isEmulator()
? ANR_INCREASED_TIMEOUT
: ANR_DEFAULT_TIMEOUT;
new ANRWatchDog(timeoutInterval).setANRListener(this).start();
}
I am using a simple conditional check on Build.Version.SDK_INT in the onCreate method of my application (code below) to prevent strict mode being enabled on any Android OS earlier than 2.3. Up until recently this had been working fine, but after a re-jig of my project, I receive the following error:
Could not find class 'android.os.StrictMode$ThreadPolicy$Builder', referenced from method com.myPackage.MyApp.onCreate
I have heard that the way class dependencies were evaluated and loaded changed from a static analysis of the class to a 'lazy loading' system in Android 2.0, but since I am using 2.2, I don't think this is at play. I suspect there is something elsewhere in my project structure that is causing this error, but I am at a loss as to what that might be.
Has anyone here had a similar experience and could maybe shed some light on this? Any help would be gratefully received.
Thanks in advance for your help!
Please see my code below for reference:
public class MyApp extends Application {
#Override
public void onCreate() {
// Set up strict mode
int buildInt = Build.VERSION.SDK_INT;
Log.d(LogTags.TRIGGER_CODE, String.format("Build is %d (%s)", buildInt, Build.VERSION.CODENAME));
if (buildInt >= 9) {
StrictMode.setThreadPolicy(new ThreadPolicy.Builder()
.detectCustomSlowCalls()
.detectNetwork()
.build());
StrictMode.setVmPolicy((new VmPolicy.Builder()
.detectAll()
.build()));
}
super.onCreate();
}
}
This turned out to be just a symptom of another problem elsewhere in code, far too specific to the project to be worth going into here...
Thanks for the thoughts on the root cause here, and sorry for the 'doh' moment :)
I have an app which uses Google Maps (v1) and from the crash reports, I am seeing this exception from time to time:
java.lang.NoClassDefFoundError: android.security.MessageDigest
at com.google.android.maps.KeyHelper.getSignatureFingerprint(KeyHelper.java:60)
at com.google.android.maps.MapActivity.createMap(MapActivity.java:513)
at com.google.android.maps.MapActivity.onCreate(MapActivity.java:409)
I have defined
<uses-library
android:name="com.google.android.maps"
android:required="true" />
inside the application tag and I am extending MapActivity as well. The application works fine on most devices but there are some uncommon ones that report this exception, usually on Android 4.0.4 like Woxter Tablet PC 90BL, TAB9008GBBK and other generic names.
From what I read in Stackoverflow, it is a problem in the ROM and it can be solved by the user doing some advanced tricks but what I want is to prevent this crash, as I don't think it can be solved, I just want to inform the user (and thell him to buy a better device :) and disable maps functionality instead of crashing. But I can't find a way to handle this error or test it with the devices I have.
Also my main activity is based on MapActivity so I don't know how can I handle this exception before opening it.
Disclaimer: I've not come across this error on any of my apps / devices but I solved a similar problem. May be that same technique can help you.
Given that the class is either unavailable or an exception occurrs while loading the class, why not try to force load it when your application starts ? Class.forName("android.security.MessageDigest") should load the class and you can catch the Error thrown from that call. I know its dirty, but it should work. You can declare a custom Application class on the manifest to make this check.
Class loading test
try
{
Class.forName("android.security.MessageDigest");
}
catch (Throwable e1)
{
e1.printStackTrace();
//Bad device
}
You can also perform a litmus test and check the functionality of the class should the class loading succeed by digesting a simple String.
Functional test
try
{
MessageDigest digester = MessageDigest.getInstance("MD5");
digester.update("test".getBytes("UTF-8"));
byte[] digest = digester.digest();
}
catch (Throwable e1)
{
e1.printStackTrace();
// Class available but not functional
}
If the class loading / litmus test fails, update a shared preference flag and let the user know that his device sucks :)
Try to change the import android.security.MessageDigest to java.security.MessageDigest
by the look at this link:
What is 'android.security.MessageDigest''?
It looks that the android.security.MessageDigest was remove from Honeycomb so change it to the java one. and check this link as well:
http://productforums.google.com/forum/#!category-topic/maps/google-maps-for-mobile/KinrGn9DcIE
As been suggested there by #XGouchet:
Try downloading the latest version of the Google Maps API and rebuild your application with targetSDK set to the highest available (as of today it should be 17 / Jelly Bean).
The class android.security.MessageDigest is an abstract class (see MessageDigest API) what means that it can't be instantiated right away. So what happens is, that any time a device/app can't find an implementation of this class you will get the exception above, namely
java.lang.NoClassDefFoundError: android.security.MessageDigest
It's a good question why this happens. May be some phone vendors didn't ship their phone with the required library that actually implements this abstract class. I faced a similar issue with the TUN.ko module in the past.
Approach 1
What should help is, if you provide your own (empty) implementation of this class that "implements" the abstract classes and methods like this:
public class MessageDigestSpi extends Object {
byte[] engineDigest() { return new byte[0]; }
void engineReset() { }
void engineUpdate(byte[] input, int offset, int len) { }
}
public class MessageDigest extends MessageDigestSpi {
}
... and put those classes into the folder <src>/java/security/. So this way you provide your own implementation that is always found and might contain some code in order to inform the user or provide an alternative implementation.
So the remaining questions are: what does the app do, if the implementation is provided by the system, too and how to control that the system implementation is the first choice?
The answer: which implementation is chosen depends on the import order. Looking at Eclipse you can define the order in the project properties, Java build path, tab order and export. Be sure that you have any system libraries on top that might include the system implementation (most likely the Android libraries). This way the system searches in those libraries first. If nothing is found your classes get loaded and executed.
Approach 2
As an alternative to the implementation in an own abstract class you could of course simply instantiate the MessageDigest class, catch the NoClassDefFoundError exception and store the result for later evaluation:
import android.security.MessageDigest;
public class MessageDigestTester {
private static Boolean messageDigestAvailable = null;
public static Boolean isLibraryAvailable() {
if (messageDigestAvailable == null) {
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
messageDigestAvailable = true;
} catch (NoClassDefFoundError e) {
messageDigestAvailable = false;
}
}
return messageDigestAvailable;
}
}
Then use if (MessageDigestTester.isLibraryAvailable()) { } else { } in your code in order to encapsulate the usage of this library and to provide an alternative.
Approach two is easier to implement whereas approach one is the more sophisticated solution.
Hope this was helpful ... Cheers!
When Android's StrictMode detects a leaked object (e.g. activity) violation, it would be helpful if I could capture a heap dump at that moment in time. There's no obvious way, however, to configure it to do this. Does anyone know of some trick that can be used to achieve it, e.g. a way to convince the system to run a particular piece of code just prior to the death penalty being invoked? I don't think StrictMode throws an exception, so I can't use the trick described here: Is there a way to have an Android process produce a heap dump on an OutOfMemoryError?
No exception, but StrictMode does print a message to System.err just before it terminates. So, this is a hack, but it works, and as it's only going to be enabled on debug builds I figure it's fine... :)
in onCreate():
//monitor System.err for messages that indicate the process is about to be killed by
//StrictMode and cause a heap dump when one is caught
System.setErr (new HProfDumpingStderrPrintStream (System.err));
and the class referred to:
private static class HProfDumpingStderrPrintStream extends PrintStream
{
public HProfDumpingStderrPrintStream (OutputStream destination)
{
super (destination);
}
#Override
public synchronized void println (String str)
{
super.println (str);
if (str.equals ("StrictMode VmPolicy violation with POLICY_DEATH; shutting down."))
{
// StrictMode is about to terminate us... don't let it!
super.println ("Trapped StrictMode shutdown notice: logging heap data");
try {
android.os.Debug.dumpHprofData(app.getDir ("hprof", MODE_WORLD_READABLE) + "/strictmode-death-penalty.hprof");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
(where app is a static field in the outer class containing a reference to the application context, for ease of reference)
The string it matches has survived unchanged from gingerbread release all the way up to jelly bean, but it could theoretically change in future versions, so it's worth checking new releases to ensure they still use the same message.
In my Android application I utilize setDefaultUncaughtExceptionHandler to store information about unhandled exceptions locally on a user device. After some feedback I suspect that this code prevents the built-in Google's error-reporting feature from work, because I do not see error reports in the developer console, while exceptions are reported by users. Their devices are well past 2.2, where the error-reporting was introduced. Could it be that specific device with, say, 4.0.3 does not support this feature? If yes, how can I detect this programmatically?
I can't find information regarding this in Android documentation. I'd like both standard error-reporting and my custom handling work together. In my custom exception handler I call Thread.getDefaultUncaughtExceptionHandler() to get default handler, and in my implementation of uncaughtException I propagate exception to this default handler as well.
I first tried calling System.exit(1); as mentioned in this SO answer, but that didn't work.
Finally solved it by calling the uncaughtException(Thread thread, Throwable ex) again on Androids default UncaughtExceptionHandler (found it by checking the ACRA source code.
Example Activity
public class MainActivity extends Activity implements Thread.UncaughtExceptionHandler {
private Thread.UncaughtExceptionHandler _androidUncaughtExceptionHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_androidUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
// Rest onCreate
setContentView(R.layout.main_activity);
}
//#Override
public void uncaughtException(Thread thread, Throwable ex) {
try {
// Do your stuff with the exception
} catch (Exception e) {
/* Ignore */
} finally {
// Let Android show the default error dialog
_androidUncaughtExceptionHandler.uncaughtException(thread, ex);
}
}
}
Yes, this will stop the inbuilt error report. The user is given a dialog when your app crashes, with an option to report the error via Google Play. However, if you use setDefaultUncaughtExceptionHandler() then the exception is handled within your app, and no option is given to report it.
I recommend that you integrate ACRA into your project, as it allows you to easily receive error reports upon crashes.