Created
November 6, 2012 06:50
-
-
Save showsky/4023106 to your computer and use it in GitHub Desktop.
Catch Crash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CrashHandler implements UncaughtExceptionHandler { | |
public static final String TAG = "CrashHandler"; | |
private static CrashHandler INSTANCE = new CrashHandler(); | |
private Context mContext; | |
private Thread.UncaughtExceptionHandler mDefaultHandler; | |
public static CrashHandler getInstance() { | |
return INSTANCE; | |
} | |
public void init(Context ctx) { | |
mContext = ctx; | |
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); | |
Thread.setDefaultUncaughtExceptionHandler(this); | |
} | |
@Override | |
public void uncaughtException(Thread thread, Throwable ex) { | |
System.out.println("uncaughtException"); | |
new Thread() { | |
@Override | |
public void run() { | |
Looper.prepare(); | |
new AlertDialog.Builder(mContext).setTitle("提示").setCancelable(false) | |
.setMessage("程序崩溃了...").setNeutralButton("我知道了", new OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
System.exit(0); | |
} | |
}) | |
.create().show(); | |
Looper.loop(); | |
} | |
}.start(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity extends Activity { | |
/** Called when the activity is first created. */ | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.main); | |
CrashHandler crashHandler = CrashHandler.getInstance(); | |
crashHandler.init(this); | |
throw new NullPointerException(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment