Android App catch Exception

来源:互联网 发布:淘宝装修队模板免费 编辑:程序博客网 时间:2024/06/15 15:02
防止app在使用过程中弹出“非常抱歉,xxx已停止运行”,在应用中实现UncaughtExceptionHandler,并在应用Application onCreate时启动线程即可,具体代码如下:
 
1.实现UncaughtExceptionHandler,并将捕获的异常信息保存到指定的文件中,方便出错后分析问题。

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

/**
 * UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序,并记录发送错误报告.
 * 
 * @author user
 * 
 */
public class CrashHandler implements UncaughtExceptionHandler {

public static final String TAG = "CrashHandler";

private Thread.UncaughtExceptionHandler mDefaultHandler;
private static CrashHandler INSTANCE = new CrashHandler();
private Context mContext;
private Map<String, String> infos = new HashMap<String, String>();

private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

private CrashHandler() {
}

public static CrashHandler getInstance() {
return INSTANCE;
}

/**
* 初始化
* @param context
*/
public void init(Context context) {
mContext = context;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}

/**
* 当UncaughtException发生时会转入该函数来处理
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if(!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(TAG, "error : ", e);
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
}

/**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
* @param ex
* @return true:如果处理了该异常信息;否则返回false.
*/
private boolean handleException(Throwable ex) {
    if(ex == null) {
        return false;
    }
// 使用Toast来显示异常信息
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();
collectDeviceInfo(mContext);
saveCrashInfo2File(ex);
return true;
}

/**
* 收集设备参数信息
* @param ctx
*/
public void collectDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
if(pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = pi.versionCode + "";
infos.put("versionName", versionName);
infos.put("versionCode", versionCode);
}
} catch (NameNotFoundException e) {
Log.e(TAG, "an error occured when collect package info", e);
}
Field[] fields = Build.class.getDeclaredFields();
for(Field field : fields) {
try {
field.setAccessible(true);
infos.put(field.getName(), field.get(null).toString());
Log.d(TAG, field.getName() + " : " + field.get(null));
} catch (Exception e) {
Log.e(TAG, "an error occured when collect crash info", e);
}
}
}

/**
* 保存错误信息到文件中
* @param ex
* @return
*/
private String saveCrashInfo2File(Throwable ex) {

StringBuffer sb = new StringBuffer();
for(Map.Entry<String, String> entry : infos.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value + "\n");
}

Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while(cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
printWriter.close();
String result = writer.toString();
sb.append(result);
try {
long timestamp = System.currentTimeMillis();
String time = formatter.format(new Date());
String fileName = "crash-" + time + "-" + timestamp + ".txt";
String path = "/mnt/sdcard/musicCrash/";
File dir = new File(path);
if(!dir.exists()) {
dir.mkdirs();
}

if(dir.listFiles().length > 50) {
for(File file : dir.listFiles()) {
if(dir.listFiles().length > 50) {
file.delete();
}
}
}
FileOutputStream fos = new FileOutputStream(path + fileName);
Log.e(TAG, new String(sb));
fos.write(sb.toString().getBytes());
fos.close();
return fileName;
} catch (Exception e) {
Log.e(TAG, "an error occured while writing file...", e);
}
return null;
}
}

2.在应用的Application中启动UncaughtExceptionHandler来监听应用的异常。

public class MyApplication extends Application {

   
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "application oncreate-----");

CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init(getApplicationContext());

}
   
}

0 0
原创粉丝点击