「android開発」グルーバル例外(exception)を処理するサンプルコード

1.例外(exception)クラスの定義 
参考コード:
package exception;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;

import android.content.Context;
import android.util.Log;

public class HandlerException implements UncaughtExceptionHandler {

private static final String TAG = “HandlerException";

private Context context;
private Thread.UncaughtExceptionHandler mDefaultHandler;

private static HandlerException mHandlerException = new HandlerException();

private HandlerException() {
}

public static HandlerException getInstance() {
return mHandlerException;
}

public void init(Context context) {
this.context = context;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}

@Override
public void uncaughtException(Thread thread, Throwable e) {
//デフォルトの例外処理
if (!handlerException(e) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, e);
} else {
// 例外処理済み場合終了
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {

}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}

}

public boolean handlerException(Throwable e) {
if (e == null)
return false;
final String msg = e.getLocalizedMessage();
final StackTraceElement[] stack = e.getStackTrace();
final String message = e.getMessage();
Log.d(TAG, msg);
Log.d(TAG, message);
//ローカルで例外ログを保存
try {
//テスト失敗場合
FileOutputStream fos = context.openFileOutput(“/Android/log_startnews24.txt",
context.MODE_PRIVATE);
fos.write(message.getBytes());
fos.flush();
fos.close();
/*File log = new File(“log_startnews24.txt");
if(!log.exists())
log.mkdirs();
FileOutputStream outputStream = new FileOutputStream(log);
outputStream.write(message.getBytes());
for (int i = 0; i < stack.length; i++) {
outputStream.write(stack.toString().getBytes());
}
outputStream.flush();
outputStream.close();*/
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
//例外処理終了,trueが戻る
//例外処理終了しない,falseが戻る
return false;
}

}

2.例外クラスを呼び出す
参考コード:
import exception.HandlerException;
import android.app.Application;

public class My_startnews24 extends Application {
private static My_startnews24 instance;
private HandlerException handlerException;

public My_startnews24() {
instance = this;
}

public static My_startnews24 getInstance() {
return instance;
}

@Override
public void onCreate() {
super.onCreate();
handlerException = HandlerException.getInstance();
handlerException.init(getApplicationContext());
}
}

Android

Posted by arkgame