工作闲暇之余断断续续看了大半《Android开发艺术探索》,收获颇丰。
以前思考过一个问题如果APP已经上线了,但是在用户手中出现了Crash现象,由于看不到崩溃日志怎样才能及时更改bug呢?
这本书给了我一个很好的答案(有三方实现,但是我觉得掌握原理也是开发者进阶的一个必要阶段)。
Thread类中的setDefaultUncaughtExceptionHandler方法完美解决了这个问题:
public static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) {
Thread.defaultUncaughtHandler = eh;
}
当Crash发生的时候,系统会调用UncaughtExceptionhandler的uncaughtException方法,再方法中就可以获取到异常信息.
首先需要实现一个UncaughtExceptionHandler对象,在他的uncaughtException方法中获取异常信息并将其存储在SD卡中或者上传服务器。
具体实现如下(参照Android开发艺术探索):
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static final String TAG = "CrashHandler";
private static final boolean DEBUG = true;
private static final String PATH = Environment.getExternalStorageDirectory().getPath()+"/CrashTest/log/";
private static final String FILE_NAME = "crash";
private static final String FILE_NAME_SUFFIX = ".trace";
private static CrashHandler sInstance = new CrashHandler();
private Thread.UncaughtExceptionHandler mDefaultCrashHandler;
private Context mContext;
public CrashHandler() {
}
public static CrashHandler getsInstance(){
return sInstance;
}
public void init(Context context){
mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
mContext = context.getApplicationContext();
}
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
try {
//导出信息到SD卡中
dumpExceptionToSDCard(throwable);
//上传异常信息到服务器
uploadExceptionToService();
}catch (IOException e){
e.printStackTrace();
}
throwable.printStackTrace();
//如果系统提供了默认的异常处理,则交给系统去结束程序,否则自己结束自己
if (mDefaultCrashHandler!=null){
mDefaultCrashHandler.uncaughtException(thread,throwable);
}else {
Process.killProcess(Process.myPid());
}
}
//导出到SDCard
private void dumpExceptionToSDCard(Throwable ex) throws IOException{
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
if (DEBUG){
Log.e("TAG", "dumpExceptionToSDCard: 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));
File file = new File(PATH+FILE_NAME+time+FILE_NAME_SUFFIX);
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", "dumpExceptionToSDCard: dump crash info failed" );
}
}
private void dumpPhoneInfo(PrintWriter pw)throws PackageManager.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 uploadExceptionToService(){
//TODO 上传服务器操作
}
}
CrashHandler的使用在BaseApplication中实例化:
public class BaseApplication extends Application{
private static BaseApplication sInstance;
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
//为应用设置异常处理,然后程序才能获取未处理的异常
CrashHandler crashHandler = CrashHandler.getsInstance();
crashHandler.init(this);
}
public static BaseApplication getsInstance(){
return sInstance;
}
}
别忘记清单文件注册:
点击按钮 手动抛出一个异常:
public class MainActivity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
throw new RuntimeException("自定义异常,点击抛出异常");
}
});
}
}
在定义的目录下找到日志文件(用小米的阅读器打开),后台提供接口的话还可以上传到服务器:
听APP崩溃日志 对于上线的APP出现Crash监听问题出处,通过运用UncaughtExceptionHandler,我们可以把崩溃日志存储到手机内存或者上传到服务器。 这样我们在后台就可以定位崩溃来源,个人觉得是一个很实用的后期项目维护手段。
如果没有《Android开发艺术探索》这本书,我有现成Demo 提供借鉴:https://github.com/ChaosOctopus/ChaosGetCrash