Android Crash 로그 캡처 프로그램 충돌 로그를 로컬 폴더에 저장
사실 원리는 매우 간단하다. 응용에 이상이 발생하면 기본적인 이상 프로세서가 이상을 처리한다. 우리가 해야 할 일은 이 임무를 인수하여 스스로 이상을 처리하는 것이다. 로그를 수집하여 로컬에 저장하고 서버에 업로드하는 것을 포함한다.
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
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");
맞다, 신청권 잊지 마세요.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Bitrise에서 배포 어플리케이션 설정 테스트하기이 글은 Bitrise 광고 달력의 23일째 글입니다. 자체 또는 당사 등에서 Bitrise 구축 서비스를 사용합니다. 그나저나 며칠 전 Bitrise User Group Meetup #3에서 아래 슬라이드를 발표했...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.