Android捕捉并收集未被程序处理的异常Exception

2014年11月19日 Android 15条评论 阅读7469次
Android捕捉并收集未被程序处理的异常Exception

在Android应用中,异常(Exception)/错误(Error)都是很常见的,为了让自己的android应用程序更加稳健、不至于很容易异常死掉,所以我们在程序中就要注意try-catch-final的使用。但无论如何,程序员总是对程序的所有异常错误都无法完全预知,这样就出现了程序极不友好的提示,给用户带来很不好的体验效果。而一旦发生了异常/错误的情况,只给程序员提供一个出错了的信息,相信诸程序员也只能无奈地摇头叹气。
基于上述问题,我们想要把未捕捉到的异常/错误信息及时保存到日志文件中,根据需要让用户提供日志文件或选择网络上传发送等。
其实,在java中jdk已经给我们提供了这样一个解决异常处理类。这就是java.lang.Thread.UncaughtExceptionHandler类。
自己只需写一个类来实现Thread.UncaughtExceptionHandler,具体未捕捉的异常处理就在uncaughtException里写就可以了。最后这个类只要在android应用的MainActivity或Application类中的onCreate中注册一次即可。
下面是一个写好的UncaughtExceptionHandler类,实现的功能就是程序遇到未知的异常时,通过Toast的形式向用户提示“很抱歉,程序出现异常,即将退出...”;同时向手机存储中制定文件夹的指定文件中保存出现异常时的设备信息(手机型号、手机生产厂商、OS版本、内核版本等)、时间、具体的StackTrace等信息;最后程序的结局肯定还是终止掉,或你可以根据自己的需求重新启动应用等。
得到出现异常的日志后,则可选择上传到网络服务器等操作了。
具体参照下面的代码。

package yourpackage;

import ......

public class CatchOtherExceptions implements Thread.UncaughtExceptionHandler {

    private static final String TAG = "CatchOtherExceptions";
    private static final String FOLDER = "Log";
    private static CatchOtherExceptions instance = null;
    private static Context mContext = null;

    // 系统默认的 UncaughtException 处理类
    private static Thread.UncaughtExceptionHandler mDefaultHandler;

    // 用来存储设备信息和异常信息
    private Map<String, String> infos = new HashMap<String, String>();

    // 用于格式化日期,作为日志文件名的一部分
    private DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");

    private CatchOtherExceptions() {
    }

    public static CatchOtherExceptions getInstance(Context c) {
        mContext = c;
        if (instance == null) {
            instance = new CatchOtherExceptions();
        }

        // 获取系统默认的 UncaughtException 处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();

        return instance;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Log.e(TAG, "error : ", e);
            }

            // 退出程序,注释下面的重启启动程序代码
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);

        }
    }

    /**
     * 自定义错误处理,收集错误信息,发送错误报告等操作均在此完成
     * 
     * @param ex
     * @return true:如果处理了该异常信息;否则返回 false
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }

        // 使用 Toast 来显示异常信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出...",
                        Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }.start();

        // 收集设备参数信息
        collectDeviceInfo(mContext);
        // 保存日志文件
        saveCrashInfo2File(ex);
        return true;
    }

    /**
     * 收集设备参数信息
     * 
     * @param ctx
     */
    public void collectDeviceInfo(Context ctx) {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.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 (NameNotFoundException e) {
            Log.e(TAG, "an error occured when collect package info", e);
        }

        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                infos.put(field.getName(), field.get(null).toString());
                Log.d(TAG, field.getName() + " : " + field.get(null));
            } catch (Exception e) {
                Log.e(TAG, "an error occured when collect crash info", e);
            }
        }
    }

    /**
     * 保存错误信息到文件中
     * 
     * @param ex
     * @return 返回文件名称,便于将文件传送到服务器
     */
    private String saveCrashInfo2File(Throwable ex) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();

        String result = writer.toString();
        sb.append(result);
        try {
            long timestamp = System.currentTimeMillis();
            String time = formatter.format(new Date());
            String fileName = "crash-" + time + "-" + timestamp + ".log";

            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                String path = Environment.getExternalStorageDirectory()
                        .getPath() + File.separator + FOLDER;
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path
                        + File.separator + fileName);
                fos.write(sb.toString().getBytes());
                fos.close();
            }

            return fileName;
        } catch (Exception e) {
            Log.e(TAG, "an error occured while writing file...", e);
        }

        return null;
    }
}
在MainActivity或应用程序的Application类的onCreate方法中加入下面的代码

Thread.setDefaultUncaughtExceptionHandler(CatchOtherExceptions.getInstance((this)));


各位在使用的时候,可能需要修改的就是要保存的路径,上面的例子是直接存到了存储的Log文件夹中。

文末,有问题欢迎提出。

分享本文至:

WRITTEN BY

avatar
本文标签:exception
看了本文是不是觉得很赞,那就赶紧点击下面按钮分享给身边的朋友吧!

15 条评论

  1. <a href="http://www.ptsbarwinslow.com/nike-air-max-06-run-oransje-obuvi">nike air max 06 run oransje</a> <a href="http://www.sarhallafk.com/nike-hyperrev-2015-bianca-nero-scarpek">nike hyperrev 2015 bianca nero</a> <a href="http://www.philippikus.com/adidas-tubular-radial-triple-white-shoesi">adidas tubular radial triple white</a> <a href="http://www.pngoilgas.com/adidas-zx-850-verde-azul-zapatosi">adidas zx 850 verde azul</a> <a href="http://www.goficarwash.com/adidas-pr%C3%B8dator-2012-skoh">adidas pr酶dator 2012</a> <a href="http://www.getairtijuana.com/nike-lebron-xiii-maschio-multi-color-university-rosso-bianca-scarpei">nike lebron xiii maschio multi color university rosso bianca</a>
    kahawellness http://www.kahawellness.com/

  2. <a href="http://www.godsentmusic.com/asics-gel-kinsei-4-laufen-schuhe-dam%C3%A4nner-gelb-obuvd">asics gel kinsei 4 laufen schuhe dam盲nner gelb</a> <a href="http://www.itmontwitter.com/free-4.0-flyknit-turnschuhe-key-scarpea">free 4.0 flyknit turnschuhe key</a> <a href="http://www.kolsyreis.com/nike-air-max-2017-kpu-ii-dark-bl%C3%A5-r%C3%B8d-schuheb">nike air max 2017 kpu ii dark bl氓 r酶d</a> <a href="http://www.ritaburton.com/womens-nike-dallas-cowboys-27-jourdan-lewis-game-black-fashion-nfl-jersey-nflr">womens nike dallas cowboys 27 jourdan lewis game black fashion nfl jersey</a> <a href="http://www.blanchardsvac.com/youth-nike-baltimore-ravens-46-morgan-cox-limited-red-2017-pro-bowl-nfl-jersey-nflx">youth nike baltimore ravens 46 morgan cox limited red 2017 pro bowl nfl jersey</a> <a href="http://www.cesafetyprod.com/hombres-nike-sb-stefan-janoski-max-blanco-azul-schuheg">hombres nike sb stefan janoski max blanco azul</a>
    broadcastgg http://www.broadcastgg.com/

  3. <a href="http://www.hotelfuat.com/nike-air-max-yellow-and-pink-skof">nike air max yellow and pink</a> <a href="http://www.pmisaltriver.com/white-purple-mens-nike-lunar-tempo-shoes-skob">white purple mens nike lunar tempo shoes</a> <a href="http://www.ductambag.com/san-francisco-giants-leopard-hat-size-chart-hata">san francisco giants leopard hat size chart</a> <a href="http://www.priverussia.com/nike-sb-portmore-womens-orange-black-runninge">nike sb portmore womens orange black</a> <a href="http://www.coatsfrance.com/nike-lebron-13-barn-rosa-oransje-schuhea">nike lebron 13 barn rosa oransje</a> <a href="http://www.intoloo.com/nike-lebron-11-elite-bl%C3%A5-3m-pret-scarpec">nike lebron 11 elite bl氓 3m pret</a>
    praiseti http://www.praiseti.com/

  4. <a href="http://www.alfiekaye.com/nike-mens-derwin-james-limited-green-jersey-los-angeles-chargers-nfl-33-salute-to-service-tank-top-nflw">nike mens derwin james limited green jersey los angeles chargers nfl 33 salute to service tank top</a> <a href="http://www.buyincar.com/under-armour-curry-1-low-all-gr%C3%B8nn-chaussuresa">under armour curry 1 low all gr酶nn</a> <a href="http://www.clearvieweps.com/nike-free-3.0-v5-rose-noir-butya">nike free 3.0 v5 rose noir</a> <a href="http://www.financesmiled.com/air-max-90-gs-hyper-rosa-kaufen-butyc">air max 90 gs hyper rosa kaufen</a> <a href="http://www.getwichquick.com/nike-hyperdunk-2014-id-basketbtout-chaussure-obuvf">nike hyperdunk 2014 id basketbtout chaussure</a> <a href="http://www.kareokiparty.com/yeezy-350-boost-triple-negro-huarache-kurpesa">yeezy 350 boost triple negro huarache</a>
    khoshop http://www.khoshop.com/

  5. avatar aesqmed

    <a href="http://www.saatchixblog.com/nike-free-inneva-tech-for-vente-obuvf">nike free inneva tech for vente</a> <a href="http://www.sparktheword.com/kvinders-nike-free-3.0-v4-gul-r%C3%B8d-obuvd">kvinders nike free 3.0 v4 gul r酶d</a> <a href="http://www.trublumeats.com/air-jordan-13-retro-rosa-and-grigio-yarn-kurpesg">air jordan 13 retro rosa and grigio yarn</a> <a href="http://www.valeriewiener.com/air-max-90-oransje-and-rosa-obuvb">air max 90 oransje and rosa</a> <a href="http://www.ykloans.com/nike-lunarglide-4-herre-sort-butya">nike lunarglide 4 herre sort</a> <a href="http://www.zendounagota.com/devin-hester-mens-elite-white-jersey-nike-nfl-chicago-bears-vapor-untouchable-road-23-nflu">devin hester mens elite white jersey nike nfl chicago bears vapor untouchable road 23</a>
    aesqmed http://www.aesqmed.com/

  6. avatar zumbajill

    <a href="http://www.undercoverapp.com/mackage-lightweight-down-coat-mackager">mackage lightweight down coat</a> <a href="http://www.johnshoots.com/bon-march%C3%A9-asics-gel-hyper-33-femmes-noir-sneakere">bon march茅 asics gel hyper 33 femmes noir</a> <a href="http://www.phihochwei.com/nike-air-max-boy-swag-man-footc">nike air max boy swag man</a> <a href="http://www.realtyindubai.com/nike-men-black-air-max-invigor-running-shoes-skox">nike men black air max invigor running shoes</a> <a href="http://www.oneusabank.com/nike-air-huarache-mens-limited-edition-sportsd">nike air huarache mens limited edition</a> <a href="http://www.filoxenos.com/printed-coach-bags-coachr">printed coach bags</a>
    zumbajill http://www.zumbajill.com/

  7. avatar carrollgrp

    <a href="http://www.evolutionecig.com/nike-kobe-10-gr%C3%A5-s%C3%B8lv-hvid-sort-volt-chaussuresa">nike kobe 10 gr氓 s酶lv hvid sort volt</a> <a href="http://www.georginabauer.com/baltimore-ravens-91-courtney-upshaw-white-road-nike-elite-jersey-nfle">baltimore ravens 91 courtney upshaw white road nike elite jersey</a> <a href="http://www.bootsoffprice.com/billig-nike-air-force-1-high-herre-gul-runningg">billig nike air force 1 high herre gul</a> <a href="http://www.theprintjobs.com/zdeno-chara-33-boston-bruins-reebok-premier-alternate-jersey-small-nflv">zdeno chara 33 boston bruins reebok premier alternate jersey small</a> <a href="http://www.dbajournal.com/nike-hyperdunk-2015-low-womens-gold-white-trainersa">nike hyperdunk 2015 low womens gold white</a> <a href="http://www.procomedian.com/nike-air-huarache-light-negro-scarped">nike air huarache light negro</a>
    carrollgrp http://www.carrollgrp.com/

  8. avatar peeplesvalleyfire

    <a href="http://www.bradleykountryacres.net/air-jordan-retro-12-hvit-rosa-schuhed">air jordan retro 12 hvit rosa</a> <a href="http://www.buyggmotors.net/kobe-6-orange-county-for-salg-uk-kurpesb">kobe 6 orange county for salg uk</a> <a href="http://www.calvaryneworleans.net/nike-hyperdunk-2012-bleu-and-blanc-kurpesa">nike hyperdunk 2012 bleu and blanc</a> <a href="http://www.calvarynola.net/dam%C3%A4nner-nike-free-tr-fit-rosa-blau-obuvb">dam盲nner nike free tr fit rosa blau</a> <a href="http://www.campaignribbons.net/air-jordan-13-retro-low-brave-azul-kurpesa">air jordan 13 retro low brave azul</a> <a href="http://www.camxl.net/nike-hyperdunk-son-of-dragon-for-vente-butyd">nike hyperdunk son of dragon for vente</a>
    peeplesvalleyfire http://www.peeplesvalleyfire.net/

  9. avatar dixiepundit

    <a href="http://www.bhcsboosters.com/nike-free-5.0-v2-himmelbl%C3%A5-gul-kurpesb">nike free 5.0 v2 himmelbl氓 gul</a> <a href="http://www.denisgoulart.com/nike-air-max-97-ultra-17-mens-shoe-zapatost">nike air max 97 ultra 17 mens shoe</a> <a href="http://www.donggeomdo.com/custom-painted-converse-uk-shoesz">custom painted converse uk</a> <a href="http://www.ozoessaouira.com/flyknit-trainer-electric-amarillo-cab-schuheb">flyknit trainer electric amarillo cab</a> <a href="http://www.annomaplexel.com/7-nike-limited-colin-kaepernick-mens-jersey-nfl-san-francisco-49ers-platinum-white-nflu">7 nike limited colin kaepernick mens jersey nfl san francisco 49ers platinum white</a> <a href="http://www.bringribben.com/adidas-zx-flux-weave-w-skou">adidas zx flux weave w</a>
    dixiepundit http://www.dixiepundit.com/

  10. avatar edotokyolabo

    <a href="http://www.truenthusiast.com/billig-nike-air-vapormax-dam%C3%A4nner-silber-shoesa">billig nike air vapormax dam盲nner silber</a> <a href="http://www.nrthofhere.com/nike-air-jordan-schuhe-skos">nike air jordan schuhe</a> <a href="http://www.ksjfifgmif.com/versace-mens-medusa-belt-beltr">versace mens medusa belt</a> <a href="http://www.gbwpvqyg.com/mackage-bag-all-virgin-mackagec">mackage bag all virgin</a> <a href="http://www.alannacaldas.com/le-coq-sportif-sneakers-south-africa-skow">le coq sportif sneakers south africa</a> <a href="http://www.lmbaidu.com/chafin-andrew-40-jersey-youth-nflc">chafin andrew 40 jersey youth</a>
    [url=http://www.edotokyolabo.com/]edotokyolabo[/url]

  11. avatar trionbrain

    <a href="http://www.bharatovation.com/nike-lebron-15-kvinders-s%C3%B8lv-sneakere">nike lebron 15 kvinders s酶lv</a> <a href="http://www.charleyscafe.com/wmns-nike-free-tr-flyknit-5.0-green-white-footc">wmns nike free tr flyknit 5.0 green white</a> <a href="http://www.hopingforsnow.com/new-balance-420-size-10-skox">new balance 420 size 10</a> <a href="http://www.housemykonos.com/asics-gel-lyte-5-mens-silver-gold-sportsd">asics gel lyte 5 mens silver gold</a> <a href="http://www.maxfullforce.com/coach-kisslock-coin-purse-coachr">coach kisslock coin purse</a> <a href="http://www.guntruthers.com/deanthony-thomas-13-jersey-red-nfld">deanthony thomas 13 jersey red</a>
    trionbrain http://www.trionbrain.com/

  12. avatar Essay Yulan

    有一个你可以连接到mysql的Mysql包,可以学习如何连接这个阶段。享受更好的时间安装这个最佳区域的时间。你也可以在这里享受美好的环境。

  13. avatar 鞍山妇科医院

    感谢楼主分享,收藏了慢慢看,慢慢学

  14. avatar LED display

    博主是专门开发android的吗,好厉害哇。

  15. avatar 琉璃瓦

    博主高手啊。来看看博主。加油

欢迎留言




用户登录

sitemap