I\'ve tried both the example in Oracle\'s Java Tutorials. They both compile fine, but at run-time, both come up with this error:
Exception in thread \"main\"
Check that if you have a static handler in your class. If so, please be careful, cause static handler only could be initiated in thread which has a looper, the crash could be triggered in this way:
1.firstly, create the instance of class in a simple thread and catch the crash.
2.then call the field method of Class in main thread, you will get the NoClassDefFoundError.
here is the test code:
public class MyClass{
private static Handler mHandler = new Handler();
public static int num = 0;
}
in your onCrete method of Main activity, add test code part:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//test code start
new Thread(new Runnable() {
@Override
public void run() {
try {
MyClass myClass = new MyClass();
} catch (Throwable e) {
e.printStackTrace();
}
}
}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MyClass.num = 3;
// end of test code
}
there is a simple way to fix it using a handlerThread to init handler:
private static Handler mHandler;
private static HandlerThread handlerThread = new HandlerThread("newthread");
static {
handlerThread.start();
mHandler = new Handler(handlerThread.getLooper(), mHandlerCB);
}