捕获异常

package com.example.day01;

import android.app.Application;

/**
 * Created by lenovo on 2018/9/15.
 */

public class app extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        yc.getInstance().my(this);
    }
}

yc

package com.example.day01;

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


/**
 * Created by lenovo on 2018/9/15.
 */

public class yc implements Thread.UncaughtExceptionHandler {
    private static final yc ourInstance = new yc();
    private Context context;
    private Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler;

    public static yc getInstance() {
        return ourInstance;
    }

    private yc() {

    }

    public  void  my(Context context){

         //捕获当前异常的方法
        Thread.setDefaultUncaughtExceptionHandler(this);
        this.context = context;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        Log.d("aaa", "thread:" + thread);

    }
}

Main

package com.example.day01;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private TextView title1;
    int i;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        title1 = findViewById(R.id.title1);
        title1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              i =  10/0;

            }
        });
    }
}

 

你可能感兴趣的:(捕获异常)