Android

例外を集約するクラス

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

/**
 * Created by androidyue on 11/23/15.
 */
public class TestUncaughtExceptionHandler  implements  Thread.UncaughtExceptionHandler{
    private static final String LOGTAG = "TestUncaughtExceptionHandler";
    private Thread.UncaughtExceptionHandler mDefaultExceptionHandler;
    private Context mAppContext;

    public TestUncaughtExceptionHandler(Context context) {
        mAppContext = context.getApplicationContext();
        mDefaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    public static String getProcessName(Context appContext) {
        String currentProcessName = "";
        int pid = android.os.Process.myPid();
        ActivityManager manager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == pid) {
                currentProcessName = processInfo.processName;
                break;
            }
        }
        return currentProcessName;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        String processName =  getProcessName(mAppContext);
        if (mAppContext.getPackageName().equals(processName)) {
            Log.i(LOGTAG, "uncaughtException main process");
            mDefaultExceptionHandler.uncaughtException(thread, ex);
        } else {
            Log.i(LOGTAG, "uncaughtException process name=" + processName);
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }
}

例外集約するクラスをアプリケーションに追加する

public class XXXApplication extends Application {
    private static final String LOGTAG = "XXXApplication";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(LOGTAG, "onCreate");
        Thread.setDefaultUncaughtExceptionHandler(new TestUncaughtExceptionHandler(this));
    }
}


超多機能のアクセス解析が永久無料!

コメント:



(画像の文字列を入力して下さい)

トップ   編集 凍結 差分 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2019/12/02 (月) 12:32:36 (1627d)

yVoC[UNLIMITȂ1~] ECirŃ|C Yahoo yV LINEf[^[Ōz500~`I


z[y[W ̃NWbgJ[h COiq 萔O~ył񂫁z COsیI COze