注册 CrashHandler crashHandler = CrashHandler.getInstance();

news/2024/11/9 9:50:19 标签: android

注册 CrashHandler crashHandler = CrashHandler.getInstance();

MainActivity如下:

[java]
package cn.testcrash; 
import android.app.Activity; 
import android.os.Bundle; 
/**
 * Demo描述:
 * 借助于Application自定义Crash
 * 
 * 备注说明:
 * 1 在获取Crash信息后可依据业务上传服务器或者保存至SDCard
 * 2 在uncaughtException()中的第三步——退出程序.此处只是做了
 *   最简单的处理.完备的操作请参见:
 *   http://blog.csdn.net/lfdfhl/article/details/9261147
 *   http://blog.csdn.net/lfdfhl/article/details/9260605
 *   
 * 参考资料:
 * 1 http://blog.csdn.net/xiaanming/article/details/9344703
 * 2 http://blog.csdn.net/itachi85/article/details/9102021
 * Thank you very much
 */ 
public class MainActivity extends Activity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        init(); 
    } 
    //Crash  
    private void init(){ 
        System.out.println((9727/0)+""); 
    } 
} 

package cn.testcrash;
import android.app.Activity;
import android.os.Bundle;
/**
 * Demo描述:
 * 借助于Application自定义Crash
 *
 * 备注说明:
 * 1 在获取Crash信息后可依据业务上传服务器或者保存至SDCard
 * 2 在uncaughtException()中的第三步——退出程序.此处只是做了
 *   最简单的处理.完备的操作请参见:
 *   http://blog.csdn.net/lfdfhl/article/details/9261147
 *   http://blog.csdn.net/lfdfhl/article/details/9260605
 *  
 * 参考资料:
 * 1 http://blog.csdn.net/xiaanming/article/details/9344703
 * 2 http://blog.csdn.net/itachi85/article/details/9102021
 * Thank you very much
 */
public class MainActivity extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  init();
 }
 //Crash
 private void init(){
  System.out.println((9727/0)+"");
 }
}

CrashApplication如下:

[java]
package cn.testcrash; 
import android.app.Application; 
 
public class CrashApplication extends Application { 
    @Override 
    public void onCreate() { 
        super.onCreate(); 
        CrashHandler crashHandler=CrashHandler.getInstance(); 
        //指定Crash时的处理程序  
        crashHandler.setCrashHandler(getApplicationContext()); 
    } 
} 

package cn.testcrash;
import android.app.Application;

public class CrashApplication extends Application {
 @Override
 public void onCreate() {
  super.onCreate();
  CrashHandler crashHandler=CrashHandler.getInstance();
  //指定Crash时的处理程序
  crashHandler.setCrashHandler(getApplicationContext());
 }
}

CrashHandler如下:

[java]
package cn.testcrash; 
import java.lang.Thread.UncaughtExceptionHandler; 
import android.content.Context; 
import android.os.Looper; 
import android.widget.Toast; 
public class CrashHandler implements UncaughtExceptionHandler { 
    private Context mContext; 
    private static CrashHandler mCrashHandler=new CrashHandler(); 
     
    public static CrashHandler getInstance(){ 
        return mCrashHandler; 
    } 
     
    /**
     * 设置当线程由于未捕获到异常而突然终止的默认处理程序。
     */ 
    public void setCrashHandler(Context context){ 
        mContext=context; 
        Thread.setDefaultUncaughtExceptionHandler(this); 
    } 
     
    /**
     * 当发生Crash时调用该方法
     */ 
    @Override 
    public void uncaughtException(Thread thread, Throwable throwable) { 
         //1 保存错误日志到SD卡  
         Utils.saveCrashInfoToSDCard(mContext, throwable); 
         //2 提示Crash信息  
         showCrashTipToast(); 
         try { 
            Thread.sleep(3000); 
        } catch (Exception e) { 
        } 
         //3 退出应用  
         System.exit(0); 
    } 
     
    private void showCrashTipToast() { 
        new Thread(new Runnable() { 
            @Override 
            public void run() { 
                Looper.prepare(); 
                Toast.makeText(mContext, "I am very sorry", Toast.LENGTH_LONG).show(); 
                Looper.loop(); 
            } 
        }).start(); 
    } 
 
} 

package cn.testcrash;
import java.lang.Thread.UncaughtExceptionHandler;
import android.content.Context;
import android.os.Looper;
import android.widget.Toast;
public class CrashHandler implements UncaughtExceptionHandler {
 private Context mContext;
 private static CrashHandler mCrashHandler=new CrashHandler();
 
 public static CrashHandler getInstance(){
  return mCrashHandler;
 }
 
 /**
  * 设置当线程由于未捕获到异常而突然终止的默认处理程序。
  */
 public void setCrashHandler(Context context){
  mContext=context;
  Thread.setDefaultUncaughtExceptionHandler(this);
 }
 
 /**
  * 当发生Crash时调用该方法
  */
 @Override
 public void uncaughtException(Thread thread, Throwable throwable) {
   //1 保存错误日志到SD卡
         Utils.saveCrashInfoToSDCard(mContext, throwable);
         //2 提示Crash信息
         showCrashTipToast();
         try {
   Thread.sleep(3000);
  } catch (Exception e) {
  }
         //3 退出应用
         System.exit(0);
 }
 
 private void showCrashTipToast() {
  new Thread(new Runnable() {
   @Override
   public void run() {
    Looper.prepare();
    Toast.makeText(mContext, "I am very sorry", Toast.LENGTH_LONG).show();
    Looper.loop();
   }
  }).start();
 }

}

Utils如下:

[java]
package cn.testcrash; 
import java.io.PrintWriter; 
import java.io.StringWriter; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import java.util.HashMap; 
import java.util.Map; 
import java.util.TimeZone; 
import android.content.Context; 
import android.content.pm.PackageInfo; 
import android.content.pm.PackageManager; 
import android.content.pm.PackageManager.NameNotFoundException; 
import android.os.Build; 
 
public class Utils { 
 
    public static void saveCrashInfoToSDCard(Context context, Throwable throwable) { 
        StringBuilder crashInfoStringBuilder=new StringBuilder(); 
         
        //获取Crash时间  
        String crashTime=getCrashTime(); 
        crashInfoStringBuilder.append("------------------"+"\n"); 
        crashInfoStringBuilder.append(crashTime+"\n"); 
        crashInfoStringBuilder.append("------------------"+"\n"); 
         
        //获取Crash时设备及该App的基本信息  
        HashMap<String, String> hashMap=getBaseInfo(context); 
        for(Map.Entry<String, String> entry:hashMap.entrySet()){ 
            String key=entry.getKey(); 
            String value=entry.getValue(); 
            crashInfoStringBuilder.append(key).append("=").append(value).append("\n"); 
        } 
        crashInfoStringBuilder.append("------------------"+"\n"); 
         
        //获取导致Crash的时间  
        String uncaughtException=getUncaughtException(throwable); 
        crashInfoStringBuilder.append(uncaughtException+"\n"); 
        crashInfoStringBuilder.append("------------------"+"\n"); 
         
        System.out.println("crashInfo如下:"+"\n"+crashInfoStringBuilder.toString()); 
         
    } 
    /**
     * 获取设备及该App的基本信息
     */ 
    public static HashMap<String, String> getBaseInfo(Context context){ 
        HashMap<String, String> hashMap = new HashMap<String, String>(); 
        PackageManager packageManager = context.getPackageManager(); 
        PackageInfo packageInfo = null; 
        try { 
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES); 
        } catch (NameNotFoundException e) { 
            e.printStackTrace(); 
        } 
         
        hashMap.put("versionName", packageInfo.versionName); 
        hashMap.put("versionCode", packageInfo.versionCode+""); 
         
        hashMap.put("MODEL",  Build.MODEL+""); 
        hashMap.put("SDK_INT",Build.VERSION.SDK_INT+""); 
        hashMap.put("RELEASE",Build.VERSION.RELEASE+""); 
        hashMap.put("PRODUCT",Build.PRODUCT+""); 
         
         
        return hashMap; 
    } 
    /**
     * 获取造成Crash的异常的具体信息
     */ 
    public static String getUncaughtException(Throwable throwable){ 
        StringWriter stringWriter = new StringWriter(); 
        PrintWriter printWriter = new PrintWriter(stringWriter); 
        throwable.printStackTrace(printWriter); 
        printWriter.close(); 
        String uncaughtException=stringWriter.toString(); 
        return uncaughtException; 
 
    } 
     
    /**
     * 获取Crash的时间
     */ 
    public static String getCrashTime(){ 
        String currentTime=""; 
        long currentTimeMillis=System.currentTimeMillis(); 
        System.setProperty("user.timezone", "Asia/Shanghai");   
        TimeZone timeZone = TimeZone.getTimeZone("Asia/Shanghai");   
        TimeZone.setDefault(timeZone);   
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); 
        Date currentDate=new Date(currentTimeMillis); 
        currentTime = simpleDateFormat.format(currentDate);   
        return currentTime; 
    } 
} 

package cn.testcrash;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;

public class Utils {

 public static void saveCrashInfoToSDCard(Context context, Throwable throwable) {
  StringBuilder crashInfoStringBuilder=new StringBuilder();
  
  //获取Crash时间
  String crashTime=getCrashTime();
  crashInfoStringBuilder.append("------------------"+"\n");
  crashInfoStringBuilder.append(crashTime+"\n");
  crashInfoStringBuilder.append("------------------"+"\n");
  
  //获取Crash时设备及该App的基本信息
  HashMap<String, String> hashMap=getBaseInfo(context);
  for(Map.Entry<String, String> entry:hashMap.entrySet()){
   String key=entry.getKey();
   String value=entry.getValue();
   crashInfoStringBuilder.append(key).append("=").append(value).append("\n");
  }
  crashInfoStringBuilder.append("------------------"+"\n");
  
  //获取导致Crash的时间
  String uncaughtException=getUncaughtException(throwable);
  crashInfoStringBuilder.append(uncaughtException+"\n");
  crashInfoStringBuilder.append("------------------"+"\n");
  
        System.out.println("crashInfo如下:"+"\n"+crashInfoStringBuilder.toString());
       
 }
 /**
  * 获取设备及该App的基本信息
  */
 public static HashMap<String, String> getBaseInfo(Context context){
  HashMap<String, String> hashMap = new HashMap<String, String>();
  PackageManager packageManager = context.getPackageManager();
  PackageInfo packageInfo = null;
  try {
   packageInfo = packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
  } catch (NameNotFoundException e) {
   e.printStackTrace();
  }
  
  hashMap.put("versionName", packageInfo.versionName);
  hashMap.put("versionCode", packageInfo.versionCode+"");
  
  hashMap.put("MODEL",  Build.MODEL+"");
  hashMap.put("SDK_INT",Build.VERSION.SDK_INT+"");
  hashMap.put("RELEASE",Build.VERSION.RELEASE+"");
  hashMap.put("PRODUCT",Build.PRODUCT+"");
  
  
  return hashMap;
 }
 /**
  * 获取造成Crash的异常的具体信息
  */
 public static String getUncaughtException(Throwable throwable){
  StringWriter stringWriter = new StringWriter();
  PrintWriter printWriter = new PrintWriter(stringWriter);
  throwable.printStackTrace(printWriter);
  printWriter.close();
  String uncaughtException=stringWriter.toString();
  return uncaughtException;

 }
 
 /**
  * 获取Crash的时间
  */
 public static String getCrashTime(){
  String currentTime="";
  long currentTimeMillis=System.currentTimeMillis();
  System.setProperty("user.timezone", "Asia/Shanghai"); 
  TimeZone timeZone = TimeZone.getTimeZone("Asia/Shanghai"); 
  TimeZone.setDefault(timeZone); 
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
  Date currentDate=new Date(currentTimeMillis);
  currentTime = simpleDateFormat.format(currentDate); 
        return currentTime;
 }
}
 

AndroidManifest.xml如下:

[html]
<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="cn.testcrash" 
    android:versionCode="1" 
    android:versionName="1.0" > 
 
    <uses-sdk 
        android:minSdkVersion="8" 
        android:targetSdkVersion="8" /> 
 
    <application 
        android:name="cn.testcrash.CrashApplication" 
        android:allowBackup="true" 
        android:icon="@drawable/ic_launcher" 
        android:label="@string/app_name" 
        android:theme="@style/AppTheme" > 
        <activity 
            android:name="cn.testcrash.MainActivity" 
            android:label="@string/app_name" > 
            <intent-filter> 
                <action android:name="android.intent.action.MAIN" /> 
 
                <category android:name="android.intent.category.LAUNCHER" /> 
            </intent-filter> 
        </activity> 
    </application> 
 
</manifest> 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.testcrash"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />

    <application
        android:name="cn.testcrash.CrashApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="cn.testcrash.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
main.xml如下:

[html]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
     > 
 
    <TextView 
        android:id="@+id/textView" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="自定义Crash"  
        android:layout_centerInParent="true" 
        android:textSize="28sp" 
    /> 
 
</RelativeLayout> 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="自定义Crash"
        android:layout_centerInParent="true"
        android:textSize="28sp"
    />

</RelativeLayout>
 

 



http://www.niftyadmin.cn/n/1335567.html

相关文章

还在让WiFi被人蹭网?学会这四招,没人蹭的WiFi网速至少快三倍

不知道小伙伴们有没有这样的困扰&#xff0c;自己的手机WiFi信号明明满格&#xff0c;为什么手机却还是卡的要死&#xff0c;难道又要换手机了&#xff1f;还是说运营商在嫉妒我&#xff1f;其实这是隔壁老王在蹭你的网&#xff0c;那么遇到这种情况你该怎么办呢&#xff1f; 今…

NDK编译OpenSSL

Openssl-1.1.1d 和此前的其他编译不同&#xff0c;不要任何初始化脚本&#xff0c;运行了反而会报错。 因此需要新开窗口编译,。 ANDROID版本默认会用最高的那个版本&#xff0c;因此需要指定。 export ANDROID_NDK_HOME/opt/android-ndk-r14b ./Configure android-arm --pr…

Visual Studio2017 离线安装

Visual Studio2017的离线安装需要使用命令行来创建本地缓存 下载引导程序后&#xff0c;使用命令行来创建本地缓存&#xff0c;然后用本地缓存安装Visual Studio 步骤1-下载Visual Studio引导程序 选择你想要下载的版本&#xff0c;点此进入进行选择下载 版本FileVisual Studio…

Excel中数据也能自己朗读?这一个操作太神奇了,赶紧学起来

世界之大&#xff0c;无奇不有&#xff0c;很多实用的小技巧&#xff0c;可能在你不知道的情况下&#xff0c;别人就已经开始使用了&#xff0c;当然&#xff0c;也有很多功能是你熟悉&#xff0c;而别人不知道的&#xff0c;所以呀&#xff0c;我们需要不断的补充能量&#xf…

ServiceConnection接口的使用

首先是Service的周期问题 The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCom…

Mysql自动按月表分区

很久没有碰DB了。最近需要做一个日志表&#xff0c;因此重新拾了下。实现了下自动按月表分区 开发环境为Mysql 5.7.28 参考资料&#xff1a; Mysql分区表及自动创建分区Partition&#xff08;按日&#xff09; 核心的两个存储过程&#xff1a; auto_create_partition为创建表…

小程序创业最后的红利期

从 2017 年初&#xff0c;微信创始人张小龙宣布小程序正式上线开始&#xff0c;很多行业都在摸索着开发小程序&#xff0c;且取得了不错的成绩&#xff0c;小程序已经生长出一个相对完整的生态圈。 在这个生态圈内&#xff0c;基于去中心化的特点&#xff0c;依托微信入口省去了…

怎么把avi格式转换成mp4?用电脑转换avi格式的方法

提起视频格式相比大家首先想到的就是mp4格式&#xff0c;而往往容易忘记avi格式。而mp4格式相比avi格式由于其占用内存相对较小且兼容性相对较高的特点而成为无人不晓的视频格式。因此很多人想把占用内存相对较大的avi格式转换成mp4。下面小编就教你用迅捷视频转换器把avi格式转…