您的位置:首页 > 其它

一个可以捕获程序崩溃个 然后可以保存本地的方法

2016-06-27 11:07 399 查看
一个可以捕获程序崩溃个 然后可以保存本地的方法

public class MyApplication extends Application {
private String DIR = "";
private String NAME = "";

/**
* 为了完全退出程序调用方法 MyApplication.getInstance().addActivity(this);
* MyApplication.getInstance().exit();
*/
private static MyApplication instance_app;

// 用于存儲 Activity 的集合,方便統一关闭
private List<Activity> activityList = new LinkedList<Activity>();

public MyApplication() {}

@Override
public void onCreate() {
super.onCreate();
this.DIR = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/yuedaosurvey/log/";
this.NAME = "client_"+getCurrentDateString() + ".txt";

Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler);
}

/**
* 捕获错误信息的handler
*/
private Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {

@Override
public void uncaughtException(Thread thread, Throwable ex) {
ex.printStackTrace();
String info = null;
ByteArrayOutputStream baos = null;
PrintStream printStream = null;
try {
baos = new ByteArrayOutputStream();
printStream = new PrintStream(baos);
ex.printStackTrace(printStream);
byte[] data = baos.toByteArray();
info = new String(data);
data = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (printStream != null) {
printStream.close();
}
if (baos != null) {
baos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
writeErrorLog(info);
// 捕获异常结束程序
System.out.println("异常关闭Socket!");
PushApplication.getInstance().logout();
YDApplication.getInstance().exit();
}
};

/**
* 向文件中写入错误信息
*
* @param info
*/
protected void writeErrorLog(String info) {
File dir = new File(DIR);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, NAME);
try {
FileOutputStream fileOutputStream = new FileOutputStream(file, true);
fileOutputStream.write(info.getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

/**
* 获取当前日期
*
* @return
*/
private static String getCurrentDateString() {
String result = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());
Date nowDate = new Date();
result = sdf.format(nowDate);
return result;
}

// 单例模式获取唯一的MyApplication实例
public static MyApplication getInstance() {
if (instance_app == null) {
instance_app = new MyApplication();
}
return instance_app;
}
// 添加Activity到容器中
public void addActivity(Activity activity) {
activityList.add(activity);
}

// 遍历所有Activity并finish
public void exit() {
for (Activity aty_list : activityList) {
aty_list.finish();
}
System.exit(0);
}

public void onLowMemory() {
super.onLowMemory();
System.gc();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: