android 监听应用程序异常,输出异常日志log

1--在manifest添加:
<application android:icon="@drawable/icon" android:label="@string/login_title"
  android:theme="@style/skin"
  android:name="com.XXX.application.LauncherApplication"
  android:process="@string/process" >
 
public class LauncherApplication extends Application {
	private Context context;
	
	@Override
	public void onCreate () {
		super.onCreate();

		AppExcepiton appException = AppExcepiton.getInstance(); 
        
		appException.init(getApplicationContext()); 

		

}
2—
public class AppExcepiton implements UncaughtExceptionHandler {

	// 获取application 对象;
	private Context mContext;

	private Thread.UncaughtExceptionHandler defaultExceptionHandler;
	// 单例声明CustomException;
	private static AppExcepiton appException;

	private AppExcepiton() {
	}

	public static AppExcepiton getInstance() {
		if (appException == null) {
			appException = new AppExcepiton();
		}
		return appException;
	}

	@Override
	public void uncaughtException(Thread thread, Throwable exception) {
		// TODO Auto-generated method stub
		String path = null;
		if (defaultExceptionHandler != null) {
			String state = Environment.getExternalStorageState();
			// 判断SdCard是否存在并且是可用的
			if (Environment.MEDIA_MOUNTED.equals(state)) {
				path = Environment.getExternalStorageDirectory().getPath();
			}
			// 创建一个logcat目录
			path = path + "/eIVS/log";
			File file = new File(path);
			if (!file.exists()) {
				file.mkdir();
			}
			String time = getCurrentTime();
			String fileName = time.substring(0, 9);
			File myFile = new File(path+"/"+fileName+".log");
			String str = "\n"+time+"-->"+"["+exception.getLocalizedMessage()+"]";
			try {
				FileWriter fw = new FileWriter(myFile, true);
				fw.write(str);
				fw.flush();
				fw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			Log.e("tag", "exception >>>>>>>" + exception.getLocalizedMessage());
			// 将异常抛出,则应用会弹出异常对话框.这里先注释掉
			// defaultExceptionHandler.uncaughtException(thread, exception);

		}
	}
	/**
	 * 获得当前时间
	 * @return
	 */
	public String getCurrentTime(){
		Time t = new Time();
		t.setToNow();
		int year = t.year;
		int month = t.month+1;
		int day =  t.monthDay;
		int hour = t.hour;
		int minute = t.minute;
		int second =  t.second;
		String time = year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second;
		return time;
		
	}
	public void init(Context context) {
		mContext = context;
		defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

3--在一个activity中模拟异常:
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.login);
  // 初始化资源信息
  throw new RuntimeException("--------");
//  init();
 
 }
/**
  * 删除超过一年的日志
  * @param path
  */
 public void deleteOldFile(final String path){
  File file = new File(path);
  file.list(new FilenameFilter() {
   
   @Override
   public boolean accept(File dir, String filename) {
    // TODO Auto-generated method stub
    File file = new File(path+"/"+filename);
    Long ago = file.lastModified();
    Long now = System.currentTimeMillis();
    //如果最后一次修改时间超过一年:3153600秒
    if((now-ago) > 31536000){
     file.delete();
    }
    return false;
   }
  });
  
 }
//打印 有用信息 能够指出 错误代码的行数
@Override
	public void uncaughtException(Thread thread, Throwable exception) {
		// TODO Auto-generated method stub
		StackTraceElement[] stack = exception.getCause().getStackTrace();  
		String path = null;
		if (defaultExceptionHandler != null) {
			String state = Environment.getExternalStorageState();
			// 判断SdCard是否存在并且是可用的
			if (Environment.MEDIA_MOUNTED.equals(state)) {
				path = Environment.getExternalStorageDirectory().getPath();
			}
			// 创建一个logcat目录
			path = path + "/eIVS/log";
			File file = new File(path);
			if (!file.exists()) {
				file.mkdir();
			}
			//删除过期文件
			deleteOldFile(path);
			String time = getCurrentTime();
			String fileName = time.substring(0, 9);
			File myFile = new File(path+"/"+fileName+".log");
			 try {  
				 String str = "\n"+time+"-->";
				 FileOutputStream fos = new FileOutputStream(myFile,true);
				 fos.write(str.getBytes());
                 for (int i = 0; i < stack.length; i++) {  
                     fos.write(stack[i].toString().getBytes());  
                 }  
 
                 fos.flush();  
                 fos.close();  
 
                 } catch (Exception e) {  
 
             }  }

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值