_110的博客

emil:1250@qq.com

Android 应用异常信息捕捉,邮件发送给开发者

通过UncaughtExceptionHandler捕获到全局异常信息,写到本地然后通过邮件发送开发者信箱。

  • activation.jar
  • additionnal.jar
  • mail.jar
  • android-support-v4.jar

MainActivity.java

package com.mail.activity;

import com.lxj.maildemo.R;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/**
 * 
 * @author ybf
 *
 */
public class MainActivity extends Activity {
    protected static final String TAG = "Mail";
    Button btn, btn1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn1 = (Button) super.findViewById(R.id.btn1);
        btn1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                throw new RuntimeException("自定义异常:这是自己抛出的异常");
                //int i = 1/0;
                //Toast.makeText(MainActivity.this, "邮件发送成功", Toast.LENGTH_SHORT).show();
            }
        });

    }


}

MyApplication.java

package com.mail.util;

import android.app.Application;
/**
 * 
 * @author ybf
 *
 */
public class MyApplication extends Application {

    private static MyApplication sInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;

        //在这里为应用设置异常处理程序,然后我们的程序才能捕获未处理的异常
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(this);
    }

    public static MyApplication getInstance() {
        return sInstance;
    }

}

CrashHandler.java

package com.mail.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Process;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;
/**
 * 
 * @author ybf
 *
 */
public class CrashHandler implements UncaughtExceptionHandler {
    private static final String TAG = "CrashHandler";
    private static final boolean DEBUG = true;
    private static final String PATH = Environment.getExternalStorageDirectory().getPath() + "/Email_info/log/";
    private static final String FILE_NAME = "log_";
    private String filepath;

    //log文件的后缀名
    private static final String FILE_NAME_SUFFIX = ".txt";

    private static CrashHandler sInstance = new CrashHandler();

    //系统默认的异常处理(默认情况下,系统会终止当前的异常程序)
    private UncaughtExceptionHandler mDefaultCrashHandler;

    private Context mContext;

    //构造方法私有,防止外部构造多个实例,即采用单例模式
    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        return sInstance;
    }

    //这里主要完成初始化工作
    public void init(Context context) {
        //获取系统默认的异常处理器
        mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
        //将当前实例设为系统默认的异常处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
        //获取Context,方便内部使用
        mContext = context.getApplicationContext();
    }

    /**
     * 这个是最关键的函数,当程序中有未被捕获的异常,系统将会自动调用#uncaughtException方法
     * thread为出现未捕获异常的线程,ex为未捕获的异常,有了这个ex,我们就可以得到异常信息。
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        try {
            //导出异常信息到SD卡中
            dumpExceptionToSDCard(ex);
            //这里可以通过网络上传异常信息到服务器,便于开发人员分析日志从而解决bug
            uploadExceptionToServer();
            SystemClock.sleep(1500);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //打印出当前调用栈信息
        ex.printStackTrace();

        //如果系统提供了默认的异常处理器,则交给系统去结束我们的程序,否则就由我们自己结束自己
        if (mDefaultCrashHandler != null) {
            mDefaultCrashHandler.uncaughtException(thread, ex);
        } else {
            Process.killProcess(Process.myPid());
        }

    }

    private void dumpExceptionToSDCard(Throwable ex) throws IOException {
        //如果SD卡不存在或无法使用,则无法把异常信息写入SD卡
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            if (DEBUG) {
                Log.w(TAG, "sdcard unmounted,skip dump exception");
                return;
            }
        }

        File dir = new File(PATH);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        long current = System.currentTimeMillis();
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current));
        //以当前时间创建log文件
        filepath = PATH + FILE_NAME+ current+ FILE_NAME_SUFFIX;
        File file = new File(filepath);

        Log.e(TAG, "fiel="+file);
        try {
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
            //导出发生异常的时间
            pw.println(time);

            //导出手机信息
            dumpPhoneInfo(pw);

            pw.println();
            //导出异常的调用栈信息
            ex.printStackTrace(pw);

            pw.close();
        } catch (Exception e) {
            Log.e(TAG, "dump crash info failed");
        }
    }

    private void dumpPhoneInfo(PrintWriter pw) throws NameNotFoundException {
        //应用的版本名称和版本号
        PackageManager pm = mContext.getPackageManager();
        PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
        pw.print("App Version: ");
        pw.print(pi.versionName);
        pw.print('_');
        pw.println(pi.versionCode);

        //android版本号
        pw.print("OS Version: ");
        pw.print(Build.VERSION.RELEASE);
        pw.print("_");
        pw.println(Build.VERSION.SDK_INT);

        //手机制造商
        pw.print("Vendor: ");
        pw.println(Build.MANUFACTURER);

        //手机型号
        pw.print("Model: ");
        pw.println(Build.MODEL);

        //cpu架构
        pw.print("CPU ABI: ");
        pw.println(Build.CPU_ABI);
    }

    private void uploadExceptionToServer() {
        //TODO Upload Exception Message To Your Web Server
        EmailUtil emailUtil = new EmailUtil();
        emailUtil.sendMailS(getbody(), filepath,"应用程序"+getAppName()+"发生了一个崩溃");
        Log.e(TAG, "sendemali");
    }

    public String getbody(){
        StringBuffer sb=new StringBuffer();
        try {
            dumpPhoneInfo(sb);
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return sb.toString();
    }
    public void dumpPhoneInfo(StringBuffer pw) throws NameNotFoundException {
        //应用的版本名称和版本号
        PackageManager pm = mContext.getPackageManager();
        PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
        pw.append("App Version: ");
        pw.append(pi.versionName);
        pw.append('_');
        pw.append(pi.versionCode);
        pw.append("\n");

        //android版本号
        pw.append("OS Version: ");
        pw.append(Build.VERSION.RELEASE);
        pw.append("_");
        pw.append(Build.VERSION.SDK_INT);
        pw.append("\n");

        //手机制造商
        pw.append("Vendor: ");
        pw.append(Build.MANUFACTURER);
        pw.append("\n");

        //手机型号
        pw.append("Model: ");
        pw.append(Build.MODEL);
        pw.append("\n");

        //cpu架构
        pw.append("CPU ABI: ");
        pw.append(Build.CPU_ABI);
        pw.append("\n");
    }
    /** 
     * 获取应用程序名称 
     */  
    public  String getAppName()  
    {  
        try  
        {  
            PackageManager packageManager = mContext.getPackageManager();  
            PackageInfo packageInfo = packageManager.getPackageInfo(  
                    mContext.getPackageName(), 0);  
            int labelRes = packageInfo.applicationInfo.labelRes;  
            return mContext.getResources().getString(labelRes);  
        } catch (NameNotFoundException e)  
        {  
            e.printStackTrace();  
        }  
        return null;  
    } 
}

EmailUtil.java

package com.mail.util;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class EmailUtil {
    /**
     * 
     * @author ybf
     *
     */

    class MyAuthenticator extends javax.mail.Authenticator {
        private String strUser;
        private String strPwd;

        public MyAuthenticator(String user, String password) {
            this.strUser = user;
            this.strPwd = password;
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPwd);
        }
    }

    public void sendMail(String toMail, String fromMail, String server,
            String username, String password, String title, String body,
            String attachment) throws Exception {

        Properties props = System.getProperties();// Get system properties

        props.put("mail.smtp.host", server);// Setup mail server

        props.put("mail.smtp.auth", "true");

        MyAuthenticator myauth = new MyAuthenticator(username, password);// Get
                                                                            // 发送邮件,和密码

        Session session = Session.getDefaultInstance(props, myauth);

        MimeMessage message = new MimeMessage(session); // Define message

        message.setFrom(new InternetAddress(fromMail)); // Set the from address
                                                        // 接收邮箱

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(
                toMail));// 目标邮箱
        // address
        message.setSubject(title);// Set the subject 标题

        // message.setText(MimeUtility.encodeWord(body));// Set the content

        MimeMultipart allMultipart = new MimeMultipart("mixed");

        MimeBodyPart attachPart = new MimeBodyPart();
        FileDataSource fds = new FileDataSource(attachment);
        attachPart.setDataHandler(new DataHandler(fds));
        attachPart.setFileName(MimeUtility.encodeWord(fds.getName()));

        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText(body);// 邮件内容

        allMultipart.addBodyPart(attachPart);
        allMultipart.addBodyPart(textBodyPart);
        message.setContent(allMultipart);
        message.saveChanges();
        Transport.send(message);
    }

    /**
     * 设置邮件信息
     * @param toMail
     *            接收邮箱
     * @param account
     *            发送者邮箱
     * @param password
     *            发送者邮箱密码         
     * @param server
     *            发送者邮箱服务器     
     * @param title
     *            邮件标题
     * @param body
     *            邮件内容
     * @param path
     *            附件路径
     */
    public void sendMailS(final String body, final String path,final String title) {
        new Thread(new Runnable() {
            public void run() {
                // EmailUtil emailUtil = new EmailUtil();
                try {
                    String toMail = "";
                    String account = "";
                    String password = "";
                    String server = "";
                    // emailUtil.
                    sendMail(toMail, account, server, account, password, title,
                            body, path);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}

代码路径:https://download.csdn.net/download/weixin_38148680/10408705

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38148680/article/details/79971090
文章标签: android
上一篇Launcher3分析及定制&主题实现
下一篇Android 手机启动流程图
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭