android自己获取并保存错误日志(可以通过邮件发送到自己邮箱)

本文介绍了如何在Android应用中实现异常处理和日志记录,包括自定义异常处理类、捕获并记录异常信息以及保存错误报告的方法。详细解释了在Android开发中使用自定义异常处理器、收集设备信息、版本信息和错误信息,并将其保存到文件中或发送到服务器的过程。

1.首先要在AndroidManifest.xml使用自己的Application

 <application
        android:name="com.example.Myapplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" >
<application/>

2.首先要重写Application

public class MyApplication extends Application{
@Override
public void onCreate() { 
super.onCreate();
UncaughtHandler handler=UncaughtHandler.getInstance();
handler.init(getApplicationContext());
}
}

3.最后就是异常处理的类了


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
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.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import android.annotation.SuppressLint;
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.Looper;
import android.util.Log;
import android.widget.Toast;
import com.jsle.ebag.answer.util.SPTool_Inter_info;


public class UncaughtHandler implements UncaughtExceptionHandler{
//UncaughtHandler实例
private static UncaughtHandler instance;
//系统默认的UncaughtException处理类
private Thread.UncaughtExceptionHandler handler;
//程序的context对象
private Context context;
private Map<String, String> infos;

private UncaughtHandler() {
}

public static synchronized UncaughtHandler getInstance(){
if(instance==null){
instance=new UncaughtHandler();
return instance;
}else{
return instance;
}

}

protected void init(Context context) {
this.context=context;
//获取系统默认的UncaughtException类
handler=Thread.getDefaultUncaughtExceptionHandler();
//设置该CrashHandler为程序的默认处理器
Thread.setDefaultUncaughtExceptionHandler(this);
infos=new HashMap<String, String>();

}

@Override
public void uncaughtException(Thread thread, Throwable ex) {
//      保存错误信息到本地(上线后添加上传的邮箱的操作)
// if(!handlerException(ex)&&handler!=null){ 
// handler.uncaughtException(thread, ex);
// }else{
// try {
// Thread.sleep(3000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// android.os.Process.killProcess(android.os.Process.myPid());
// System.exit(1);
// }
//~
//测试用当实际使用时用上面的代码
handlerException(ex);
if(handler!=null){
handler.uncaughtException(thread, ex);
}
//~
}
/** 
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 
     *  
     * @param ex 
* @return 
     * @return true:如果处理了该异常信息;否则返回false. 
     */  
private boolean handlerException(Throwable e) {
if(e==null){
return false;
}
//使用toast来做提示信息
new Thread(){
public void run() {
Looper.prepare();
Toast.makeText(context, "程序异常,即将关闭。", Toast.LENGTH_LONG).show();
Looper.loop();
};
}.start();
//添加信息发送或本地保存
getMobileInfo();//获取手机信息
getVersionInfo();//获取版本信息
getErrorInfo(e);//获取错误信息
saveInfo2File();
SPTool_Inter_info.writeAbnormal(context, true);
return true;

}


/**
* 获取异常信息
* @param e
* @return 异常信息
*/
private void getErrorInfo(Throwable e) {
Writer writer=new StringWriter();
PrintWriter pw=new PrintWriter(writer);
e.printStackTrace(pw);
pw.flush();
String error=writer.toString();
infos.put("error information", error);
try {
pw.close();
writer.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
/**
* 获取设备信息
* @return 
*/
private String getMobileInfo() {
StringBuffer sb=new StringBuffer();
//通过反射获取设备信息
try {
Field[] fields=Build.class.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
infos.put(field.getName(), field.get(null).toString());
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.e("UncaughtHandler", "has IllegalArgument error at method 'getMobileInfo()'");
} catch (IllegalAccessException e) {
e.printStackTrace();
Log.e("UncaughtHandler", "has IllegalAccess error at method 'getMobileInfo()'");
}
return sb.toString();
}
/**
* 获取手机
* @return 
*/
private void getVersionInfo() {
try {
PackageManager pm=context.getPackageManager();
PackageInfo pi=pm.getPackageInfo(context.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 (Exception e) {
e.printStackTrace();
Log.e("UncaughtHandler", "has error at method 'getVersionInfo()'");
}
}
@SuppressLint("SimpleDateFormat")
private void saveInfo2File() {
StringBuffer buffer=new StringBuffer();
for (Map.Entry<String, String> entry: infos.entrySet()) {
buffer.append(entry.getKey()+" = "+entry.getValue());
buffer.append("\n");
}

String time=new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(new Date(System.currentTimeMillis()));
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
String path=Environment.getExternalStorageDirectory().getAbsolutePath().toString()+File.separator+"EbagError";
String name="carsh-"+time+".log";
File filepath=new File(path);
if(!filepath.exists()||!filepath.isDirectory()){
filepath.mkdirs();
}
File file=new File(path+File.separator+name);
try {
FileOutputStream fos=new FileOutputStream(file);
fos.write(buffer.toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
 Log.e("UncaughtHandler", "an error occured while writing file...", e); 
}
}

}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值