Cause analysis and solution of Android force close exception

1、 Reason:

Forceclose means forcibly closing. The current application conflicts.

Nullpointexception (null pointer), indexoutofboundseception (subscript out of bounds), and even the wrong order of Android API may lead to a series of uncapped exceptions (such as findviewbyid() operation before setcontentview())

2、 How to avoid

How to avoid popping up the force close window, you can implement thread The uncaughtexception method code of uncaughtexceptionhandler interface is as follows:

In addition, which thread do you want to handle uncapped exceptions, thread setDefaultUncaughtExceptionHandler( this); This code must be executed once in that thread

In the uncaughtexception method, the first parameter is the thread and the second parameter is the exception.

Next, look at the log results:

08-0918:50:27.87410739-10739/example. com. force_ anrI/tag:--->>onCreate 08-0918:50:31.66410739-10739/example. com. force_ Anri / tag: forceclose is intercepted. The exception reason is:

java. lang.indexoutofboundsexception:Invalidindex1,sizeis0Thread:1

The exception is successfully caught and the activity exits, but it is not safe to exit, because when you click Open APK again, you find that the program is not responding.

In order to solve the above problems, I kill the process in the uncaughtexception method. There are many methods to kill the process. Here is a suicide method

Amend as follows:

Other procedures remain unchanged..

3. We can do this not only in the main thread, but also in the sub thread:

Then start the child thread in the life cycle of the activity to listen for the occurrence of uncapped exceptions.

Here's a question: we obviously catch exceptions in the child thread, but how does the thread ID - > 1, the thread ID - > 1, and why the thread is the main thread! This problem is discussed below.

4. Solve the problem in the third step

Let's rewrite the sub thread: set exceptions in the sub thread, and don't forget to delete the code that catches exceptions and the code that occurs exceptions in the activity.

See the following log in the startup program:

It seems to have tried to start twice. Look, the thread has changed. Therefore, arg0 in this method uncaughtexception (thread arg0, throwable arg1) refers to the thread where the exception occurred, not necessarily the thread registered by uncaughtexception.

The above is the cause analysis and solutions of Android force close exceptions introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>