android 全局异常监控

来源:互联网 发布:淘宝游戏交易 编辑:程序博客网 时间:2024/04/30 12:39

有时候android app产生异常,但是本身APP无法监控,导致APP崩溃;这里就需要用一个全局类来监控此问题

crashhandler类:


package com.crashhandler.util;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


 


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.view.WindowManager;
 
/**
 * UncaughtException处理类,当程序发生Uncaught异常的时候,由该类来接管程序,并记录发送错误报告.
 * 
 */
public class CrashHandler implements UncaughtExceptionHandler {
    // 系统默认的UncaughtException处理类
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    // CrashHandler实例
    private static CrashHandler INSTANCE;
    // 程序的Context对象
    private Context mContext;
 
    //保证只有一个CrashHandler实例 
    private CrashHandler() {
 
    }
 
    //获取CrashHandler实例 ,单例模式
    public static CrashHandler getInstance() {
        if (INSTANCE == null)
            INSTANCE = new CrashHandler();
        return INSTANCE;
    }
 
    /**
     * 初始化
     * 
     * @param context
     */
    public void init(Context context) {
        mContext = context;
        // 获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        // 设置该CrashHandler为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }
 
    /**
     * 当UncaughtException发生时会转入该重写的方法来处理
     */
    public void uncaughtException(Thread thread, Throwable ex) {
   

//这里写入异常信息到文本
    saveLog(ex.getMessage());
System.exit(0);

     
        
       /* if (!handleException(ex) && mDefaultHandler != null) {
            // 如果自定义的没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        }*/
    }
 
    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     * 
     * @param ex
     *            异常信息
     * @return true 如果处理了该异常信息;否则返回false.
     */
    public boolean handleException(Throwable ex) {
        if (ex == null || mContext == null)
            return false;
        final String crashReport = getCrashReport(mContext, ex);
        new Thread() {
            public void run() {
                Looper.prepare();
//                File file = save2File(crashReport);
//                sendAppCrashReport(mContext, crashReport, file);
                saveLog(crashReport);
                Looper.loop();
            }
 
        }.start();
        return true;
    }
 // 日子文件
  static String logFile = Environment.getExternalStorageDirectory()
  + "/Log.txt";
    public static boolean saveLog(String data) {


try {


SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
String dt = formatter.format(curDate);


File file = new File(logFile);
if (!file.exists())
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file, true);
OutputStreamWriter wt = new OutputStreamWriter(fos, "GBK");
// wt.write(data.getBytes());
wt.write(dt + "|" + data);
wt.flush();
wt.close();
fos.close();
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}

    
  
 
    /**
     * 获取App安装包信息
     * 
     * @return
     */
    private PackageInfo getPackageInfo(Context context) {
        PackageInfo info = null;
        try {
            info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
             e.printStackTrace(System.err);
        }
        if (info == null)
            info = new PackageInfo();
        return info;
    }
 
}

异常类调用:

package com.crashhandler.util;
import android.app.Application;
public class MyApplication extends Application{
    private static MyApplication mApplication;
     
    public synchronized static MyApplication getInstance() {
        return mApplication;
    }
     
    @Override
    public void onCreate() {
        super.onCreate();
        initData();
    }
 
    private void initData() {
        //当程序发生Uncaught异常的时候,由该类来接管程序,一定要在这里初始化
        CrashHandler.getInstance().init(this);
    }
 
}


APP调用此类,在配置文件添加就可

 <application
        android:name="com.crashhandler.util.MyApplication"//添加这一句就可以监控到
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >


0 0
原创粉丝点击