Android借助Application重写App的Crash(简易版)

简介: MainActivity如下: package cn.testcrash;import android.app.Activity;import android.

MainActivity如下:

package cn.testcrash;
import android.app.Activity;
import android.os.Bundle;
/**
 * Demo描述:
 * 借助于Application自定义Crash
 * 
 * 参考资料:
 * 1 http://blog.csdn.net/xiaanming/article/details/9344703
 * 2 http://blog.csdn.net/itachi85/article/details/9102021
 */
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如下:

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如下:

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) {
		 //保存错误日志到SD卡
         Utils.saveInfoToSDCard(mContext, throwable);
         //提示Crash信息
         showCrashTipToast();
         try {
			Thread.sleep(3000);
		} catch (Exception e) {
		}
         //退出应用
         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如下:

package cn.testcrash;
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 saveInfoToSDCard(Context context, Throwable throwable) {
		HashMap<String, String> hashMap=getBaseInfo(context);
		StringBuilder stringBuilder=new StringBuilder();
		for(Map.Entry<String, String> entry:hashMap.entrySet()){
			String key=entry.getKey();
			String value=entry.getValue();
			stringBuilder.append(key).append("=").append(value).append("\n");
		}
        System.out.println("stringBuilder.toString()如下:"+"\n"+stringBuilder.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;
	}
	
	
	
	private String getCurrentTime(){
		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);  
        System.out.println("currentTime="+currentTime);
        return currentTime;
	}
	 

}


main.xml如下:

<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>

 

AndroidManifest.xml如下:

<?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>



 

相关文章
|
4月前
|
XML 物联网 API
Android Ble蓝牙App(五)数据操作
Android Ble蓝牙App(五)数据操作
|
3月前
|
Android开发 开发者 iOS开发
APP开发后如何上架,上架Android应用市场前要准备什么
移动应用程序(APP)的开发已经成为现代企业和开发者的常见实践。然而,开发一个成功的APP只是第一步,将其上架到应用商店让用户下载和使用是实现其潜力的关键一步。
|
1天前
|
测试技术 Android开发
Android App获取不到pkgInfo信息问题原因
Android App获取不到pkgInfo信息问题原因
9 0
|
1月前
|
设计模式 测试技术 数据库
基于Android的食堂点餐APP的设计与实现(论文+源码)_kaic
基于Android的食堂点餐APP的设计与实现(论文+源码)_kaic
|
2月前
|
安全 Java 数据挖掘
当 App 有了系统权限,真的可以为所欲为? Android Performance Systrace
当 App 有了系统权限,真的可以为所欲为? Android Performance Systrace 转载自: https://androidperformance.com/2023/05/14/bad-android-app-with-system-permissions/#/0-Dex-%E6%96%87%E4%BB%B6%E4%BF%A1%E6%81%AF
31 0
|
3月前
|
Android开发
闲暇时间收集和整理的Android的一些常用的App
闲暇时间收集和整理的Android的一些常用的App
14 0
|
3月前
|
Android开发 UED 开发者
解释Android App Bundle是什么,它的优势是什么?
解释Android App Bundle是什么,它的优势是什么?
57 0
|
3月前
|
缓存 Java 数据库
Android 性能优化: 请解释ANR(Application Not Responding)是什么,如何避免它?
Android 性能优化: 请解释ANR(Application Not Responding)是什么,如何避免它?
49 0
|
3月前
|
JavaScript Android开发
Cordova 后台运行 Android APP
Cordova 后台运行 Android APP