您的位置:首页 > 移动开发 > Android开发

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

2016-03-21 17:33 633 查看
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>();}@Overridepublic 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 blocke1.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);}}}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: