Android/ErrorLogStack
提供: 初心者エンジニアの簡易メモ
エラーリストが取得用途
エラーレポーティング用途などで・・stacktraceエラーリストが取得できる
CustomUncaughtExceptionHandler.java
import android.content.Context; import android.content.SharedPreferences; import java.io.PrintWriter; import java.io.StringWriter; public class CustomUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { private Context mContext; private Thread.UncaughtExceptionHandler mDefaultUncaughtExceptionHandler; public CustomUncaughtExceptionHandler(Context context) { mContext = context; mDefaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); } @Override public void uncaughtException(Thread thread, Throwable ex) { StringWriter stringWriter = new StringWriter(); ex.printStackTrace(new PrintWriter(stringWriter)); String stackTrace = stringWriter.toString(); Log.d("error", "stackTrace=" + stackTrace); // stackTraceこれがstacktraceエラーリスト mDefaultUncaughtExceptionHandler.uncaughtException(thread, ex); } }
ExampleClass.java
public class ExampleClass { public static void test() { new ArrayList<String>().get(0); } } <pre> MainActivity.java <pre> import android.content.Context; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); CustomUncaughtExceptionHandler customUncaughtExceptionHandler = new CustomUncaughtExceptionHandler( getApplicationContext()); Thread.setDefaultUncaughtExceptionHandler(customUncaughtExceptionHandler); ExampleClass.test(); } }
stacktraceエラーリストサンプル
参考
https://dev.classmethod.jp/smartphone/android/android-app-exception/
https://kokufu.blogspot.com/2013/01/android-uncaughtexceptionhandler-anr.html