Android Exception Handling Best Practices

  • 2021-06-29 11:58:06
  • OfStack

A good app exception handling mechanism I think should include at least the following functions:

1. The ability to upload error information to the server allows developers to continuously improve app

2. Error messages should at least contain information such as whether the main process is on the main thread or not to help the programmer locate

3. It is best to include mobile phone hardware and software information.

4. Exceptions caused by the main process are best left to the system itself, that is, to make the user aware of that (of course, you can also define a more interesting set of awareness system dialogs, etc., referring to various interesting 404 interfaces)

5. Exceptions thrown by child processes are best not perceived by users.Such as push, which is weakly associated with user perception.It is best to drop kill directly if an exception occurs.Don't give it to the system anymore.

Code above below.


package com.example.administrator.exceptiontest;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;

/**
 * Created by Administrator on 2015/12/9.
 */
public class BaseApplication extends Application {

  public static Context mContext;
  // Default exception handling 
  public static Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler;

  @Override
  public void onCreate() {
    super.onCreate();
    mContext = this;
    // Get Default Exception Handling First handler
    defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(new BaseUncaughtExceptionHandler());
  }


}

package com.example.administrator.exceptiontest;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Looper;

/**
 * Created by Administrator on 2015/12/9.
 */
public class Utils {

  /**
   *  Determine whether to execute in the main thread   If it is returned true  Not Return false
   */
  public static boolean isInMainThread() {
    // Attention to this place   We can't 1 Definitely available myLooper Value of   For instance   Your thread  No bound message loop 
    // Then your mylooper On return 1 Must be null Yes, only after binding will the corresponding value be returned 
    return Looper.myLooper() == Looper.getMainLooper();
  }


  // Determine if it is the main process   If it is   Just go back true  Otherwise return false
  public static boolean isMainProcess(Context context)
  {
    return context.getPackageName().equals(getProcessName(context));
  }

  // Get process name 
  public static String getProcessName(Context context) {
    String currentProcessName = "";
    int pid = android.os.Process.myPid();
    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
      if (processInfo.pid == pid) {
        currentProcessName = processInfo.processName;
        break;
      }
    }
    return currentProcessName;
  }

}


package com.example.administrator.exceptiontest;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

/**
 * Created by Administrator on 2015/12/9.
 */
public class BaseUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

  @Override
  public void uncaughtException(Thread thread, Throwable ex) {
    Writer resultWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(resultWriter);
    ex.printStackTrace(printWriter);
    StringBuffer sb = new StringBuffer();
    sb.append(" Whether an exception occurred in the main thread " + Utils.isInMainThread() + "\n");
    sb.append(" Whether an exception occurred in the main process " + Utils.isMainProcess(BaseApplication.mContext) + "\n");
    String errorReport = sb.toString() + resultWriter.toString();
    // This is a good place to keep a log of errors collected   Upload to Server   Easy for developers to locate modification issues. 
    // If an exception occurs to the main process   That's left to the system's own default exception handling.Make users aware, otherwise they don't know anything   Not a good experience 
    // You can of course define your own special error alerts   such as 1 Some interesting dialog What's the 
    if (Utils.isMainProcess(BaseApplication.mContext)) {
      BaseApplication.defaultUncaughtExceptionHandler.uncaughtException(thread, ex);
    } else {
      // If an exception occurs to a child process   Don't give a hint   Direct dropping is best   Perception 
      android.os.Process.killProcess(android.os.Process.myPid());
    }
  }


}

This is the whole content of this article, and I hope it will be helpful for you to learn Android software programming.


Related articles: