Android/ErrorLogStack
提供: 初心者エンジニアの簡易メモ
エラーリストが取得用途
エラーレポーティング用途などで・・stacktraceエラーリストが取得できる
以下コードはfirebase-crashlyticsなどと併用可能だった。
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); // エラーを起こす } }
MainActivity.java
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エラーリストサンプル
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.get(ArrayList.java:308) at com.example.mycrashapplication.ExampleClass.test(GNSHogehoge.java:8) at com.example.mycrashapplication.MainActivity$1.onClick(MainActivity.java:33) at android.view.View.performClick(View.java:5231) at android.view.View$PerformClick.run(View.java:21190) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5554) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:746) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
参考
https://dev.classmethod.jp/smartphone/android/android-app-exception/
https://kokufu.blogspot.com/2013/01/android-uncaughtexceptionhandler-anr.html