Android Crash 로그 캡처 프로그램 충돌 로그를 로컬 폴더에 저장

붕괴 로그의 포획은 여러 가지 방식이 있는데 가장 직접적인 것은 삼자의 포획에 접속하는 것이다. 그러나 어떤 원인이나 원인으로 인해 붕괴 위치를 정확하게 포착하지 못한다. 또한 응용 프로그램이 테스트할 때 붕괴 위치를 더욱 잘 포착하기 위해서이다. (테스트기가 많을 때 모든 사람이 LOG와 인터럽트를 할 수 없다)
사실 원리는 매우 간단하다. 응용에 이상이 발생하면 기본적인 이상 프로세서가 이상을 처리한다. 우리가 해야 할 일은 이 임무를 인수하여 스스로 이상을 처리하는 것이다. 로그를 수집하여 로컬에 저장하고 서버에 업로드하는 것을 포함한다.
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Date;


/**
 *  

: * @author ma */ public class CrashHandler implements UncaughtExceptionHandler { // private final static String LOG_FILE_CREATE_TIME_FORMAT = "yyyy-MM-dd_HH"; private final static String LOG_FILE_SUFFIX = "_crash.log"; // private final static String LOG_RECORD_TIME_FORMAT ="yyyy-MM-dd HH:mm:ss"; private UncaughtExceptionHanlderListener mHanlderListener; private Context mContext; private static CrashHandler sInstance; // private String mLogDir; private StringBuffer sb; public static CrashHandler getInstance(Context context){ if (sInstance == null) { sInstance = new CrashHandler(context); } return sInstance; } private CrashHandler(Context context){ mContext = context; Thread.setDefaultUncaughtExceptionHandler(this); } /* (non-Javadoc) * @see java.lang.Thread.UncaughtExceptionHandler#uncaughtException(java.lang.Thread, java.lang.Throwable) */ @Override public void uncaughtException(Thread thread, Throwable ex) { Log.e("ssssssssss","cuowu1"); hanldeException(ex); if (mHanlderListener != null) { mHanlderListener.handlerUncaughtException(sb); } } /** * * @param hanlderListener : {@link UncaughtExceptionHanlderListener} */ public void setHanlderListener(UncaughtExceptionHanlderListener hanlderListener) { this.mHanlderListener = hanlderListener; } /** * * @param logDirPath */ public void setCrashLogDir(String logDirPath){ mLogDir = logDirPath; } // private void hanldeException(Throwable ex){ Log.e("ssssssssss","cuowu2"); if (ex == null) { return ; } if (CrashUtils.isSDCardAvaiable(mContext) && !TextUtils.isEmpty(mLogDir)) { saveCrashInfoToFile(ex); } } // private void saveCrashInfoToFile(Throwable ex) { Writer info = new StringWriter(); PrintWriter printWriter = new PrintWriter(info); ex.printStackTrace(printWriter); Throwable cause = ex.getCause(); while (cause != null) { cause.printStackTrace(printWriter); cause = cause.getCause(); } String content = info.toString(); printWriter.close(); StringBuffer sb = new StringBuffer(); long time = System.currentTimeMillis(); sb.append(">>>>>>>>>>>>>> "); sb.append(CrashUtils.formatDate(new Date(time), LOG_RECORD_TIME_FORMAT)); sb.append(">>>>>>>>>>>>>> "); sb.append("\r
"); sb.append(">>>>>>>>>>>>>> "); sb.append(CrashUtils.getPhoneModel(mContext)); sb.append(">>>>>>>>>>>>>> "); sb.append("\r
"); sb.append(">>>>>>>>>>>>>>IMEI "); sb.append(CrashUtils.getPhoneIMEI(mContext)); sb.append(">>>>>>>>>>>>>> "); sb.append("\r
"); sb.append(">>>>>>>>>>>>>> "); sb.append(CrashUtils.getAppVersionCode(mContext)); sb.append(">>>>>>>>>>>>>> "); sb.append("\r
"); sb.append(">>>>>>>>>>>>>> / "); sb.append(CrashUtils.getAvailMemory(mContext)+"/"+ CrashUtils.getTotalMemory(mContext)); sb.append(">>>>>>>>>>>>>> "); sb.append("\r
"); sb.append(">>>>>>>>>>>>>>IP "); sb.append(CrashUtils.getLocalIpAddress()); sb.append(">>>>>>>>>>>>>> "); sb.append("\r
"); sb.append(content); sb.append("\r
"); sb.append("\r
"); this.sb =sb; CrashUtils.writeToFile(mLogDir,generateLogFileName("error",time), sb.toString(), "utf-8"); return ; } // private String generateLogFileName(String prefix, long time){ StringBuilder sb = new StringBuilder(); sb.append(prefix); sb.append("_"); sb.append(CrashUtils.formatDate(new Date(time),LOG_FILE_CREATE_TIME_FORMAT)); sb.append(LOG_FILE_SUFFIX); return sb.toString(); } /** * */ public static interface UncaughtExceptionHanlderListener{ /** * * 、 */ public void handlerUncaughtException(StringBuffer sb); } }


CrashUtils.java
import android.Manifest;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import android.util.Log;

import com.blankj.utilcode.util.Utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

/**
 *       
 *
 * @author ma
 */
public class CrashUtils {
	//              
	private static final TimeZone GMT = TimeZone.getTimeZone("GMT+8");
	// SD          1MB
	private final static long DEFAULT_LIMIT_SIZE = 1;
	private static String imei;


/      /
	/**
	 *        
	 *
	 * @param mContext
	 * @return
	 */
	public static int getAppVersionCode(Context mContext) {
		try {
			PackageManager manager = mContext.getPackageManager();
			PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0);
			int version = info.versionCode;
			return version;
		} catch (Exception e) {
			return -1;
		}
	}

	/**
	 *     IMEI 
	 *
	 * @param mContext
	 * @return
	 */
	public static String getPhoneIMEI(Context mContext) {
		if (ActivityCompat.checkSelfPermission(Utils.getApp(), Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
			TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
			imei = telephonyManager.getDeviceId();
		}

		return imei;
	}

	/**
	 *       
	 * 
	 * @param mContext
	 * @return
	 */
	public static String getPhoneModel(Context mContext) {
		//    android   
		String manufacturer = "";
		String model = "";
		try {

			Class build_class = android.os.Build.class;
			//     
			Field manu_field = build_class.getField("MANUFACTURER");
			manufacturer = (String) manu_field.get(new android.os.Build());
			//     
			Field field2 = build_class.getField("MODEL");
			model = (String) field2.get(new android.os.Build());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return manufacturer + " " + model;
	}

	/**
	 *     IP
	 * 
	 * @return
	 */
	public static String getLocalIpAddress() {
		try {
			for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
		}
		return null;
	}

	/**
	 *   android         
	 */
	public static String getAvailMemory(Context mContext) {//   android        

		ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
		MemoryInfo mi = new MemoryInfo();
		am.getMemoryInfo(mi);  
		//mi.availMem;             

		return Formatter.formatFileSize(mContext, mi.availMem);//            
	}  

	/**
	 *        
	 */
	public static String getTotalMemory(Context mContext) {
		String str1 = "/proc/meminfo";//         
		String str2;
		String[] arrayOfString;
		long initial_memory = 0;

		try {
			FileReader localFileReader = new FileReader(str1);
			BufferedReader localBufferedReader = new BufferedReader(
					localFileReader, 8192);
			str2 = localBufferedReader.readLine();//   meminfo   ,        

			arrayOfString = str2.split("\\s+");
			for (String num : arrayOfString) {
				Log.i(str2, num + "\t");
			}

			initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;//        ,   KB,  1024   Byte
			localBufferedReader.close();

		} catch (IOException e) {
		}
		return Formatter.formatFileSize(mContext, initial_memory);// Byte   KB  MB,       
	}

	/     /

	public static String formatDate(Date date, String pattern) {
		if (date == null) {
			throw new IllegalArgumentException("date is null");
		}
		if (pattern == null) {
			throw new IllegalArgumentException("pattern is null");
		}
		SimpleDateFormat formatter = formatFor(pattern);
		return formatter.format(date);
	}
	private static final ThreadLocal>> THREADLOCAL_FORMATS = new ThreadLocal>>() {

		@Override
		protected SoftReference> initialValue() {
			return new SoftReference>(
					new HashMap());
		}
	};
	private static SimpleDateFormat formatFor(String pattern) {
		SoftReference> ref = THREADLOCAL_FORMATS.get();
		Map formats = ref.get();
		if (formats == null) {
			formats = new HashMap();
			THREADLOCAL_FORMATS.set(new SoftReference>(formats));
		}

		SimpleDateFormat format = formats.get(pattern);
		if (format == null) {
			format = new SimpleDateFormat(pattern, Locale.CHINA);
			format.setTimeZone(GMT);
			formats.put(pattern, format);
		}
		return format;
	}
	/         /
	public static void writeToFile(String dir, String fileName, String content, String encoder) {
		File file = new File(dir, fileName);
		File parentFile = file.getParentFile();
		Log.e("ssssssssss","xieru");
		OutputStreamWriter osw = null;
		BufferedWriter bw = null;
		try {
			if (!parentFile.exists()) {
				parentFile.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			osw = new OutputStreamWriter(new FileOutputStream(file, true), encoder);
			bw = new BufferedWriter(osw);
			bw.append(content);
			bw.append("\r
"); bw.flush(); } catch (IOException e) { } finally { closeSilently(bw); closeSilently(osw); } } /** * */ public static void closeSilently(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { } } } / SD / public static boolean isSDCardAvaiable(Context context) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { if (getSDFreeSize() > DEFAULT_LIMIT_SIZE) { return true; } else { // ToastUtil.showToast(context, "SD , "); return false; } } else { // ToastUtil.showToast(context, "SD "); return false; } } /** * SDCard * * @return MB */ @SuppressWarnings("deprecation") public static long getSDFreeSize() { // SD File path = Environment.getExternalStorageDirectory(); StatFs sf = new StatFs(path.getPath()); // (Byte) long blockSize = sf.getBlockSize(); // long freeBlocks = sf.getAvailableBlocks(); // SD return (freeBlocks * blockSize) / 1024 / 1024; // MB } }

Application 클래스에서 초기화
CrashHandler.getInstance(getApplicationContext()).setCrashLogDir(getCrashLogDir());

getcrashLogDir() 방법 저장 위치(PS: 일반 저장 위치는 파일 아래: 안드로이드/Data/패키지 이름/files/Download/log 아래)
protected String getCrashLogDir() {
        // TODO Auto-generated method stub
        String sb = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/log";
        return sb;
    }

MainActivity에서java 클래스에서 인위적으로 붕괴
Integer.parseInt("sss");

맞다, 신청권 잊지 마세요.
 
    

    
    
    
    

좋은 웹페이지 즐겨찾기