文章之前写过,重新整理一下。

为什么会有应用已停止运行?

运行时出现了未捕获的异常,导致程序无法正常运行。

如下面,主线程(main)出现致命异常(fatal exception)导致程序无法正常运行。

  1. # main主线程,fatal exception 致命异常
  2. AndroidRuntime: FATAL EXCEPTION: main
  3. AndroidRuntime: Process: com.la.allwater, PID: 4553
  4. AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference
  5. AndroidRuntime: at com.la.allwater.HomeMainActivity$1.onClick(HomeMainActivity.java:40)
  6. AndroidRuntime: at android.view.View.performClick(View.java:6609)
  7. AndroidRuntime: at android.view.View.performClickInternal(View.java:6582)
  8. AndroidRuntime: at android.view.View.access$3100(View.java:780)
  9. AndroidRuntime: at android.view.View$PerformClick.run(View.java:26094)
  10. AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:873)
  11. AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
  12. AndroidRuntime: at android.os.Looper.loop(Looper.java:193)
  13. AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6702)
  14. AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
  15. AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
  16. AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:994)
复制

如何定位问题了

一般这样的问题寻找关键字AndroidRuntime或者FATAL或者EXCEPTION

这三个关键字各有优点,个人比较喜欢使用fatal来定位更快一些。

解决问题

报错可以,但不能影响整个应用,因此在一些未知情况下可以使用如下方式做一定的处理。

新增判断条件

既然不支持是否为null,因此在使用前进行null判断,不为null才执行后续判断

  1. if (null != context) {
  2. context.getContentResolver();
  3. }
复制
防患未来

捕获可能存在异常的代码块。异常正常打印,不会影响整个影藏。

  1. try {
  2. context.getContentResolver();
  3. } catch (Exception e) {
  4. e.printStackTrace();
  5. }
复制

相关文章

暂无评论

none
暂无评论...