在我的Android应用程序中,我需要管理自定义Activity类中所有未捕获的异常。现在我有一个问题,我无法从里面启动一个Activity。即使活动没有开始,也没有例外。
public class MyActivity extends Activity {
Context context;
Throwable throwable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context=getApplicationContext();
final AlertDialog.Builder builder= new AlertDialog.Builder(this);
Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
throwable=ex;
new Thread(){
@Override
public void run() {
Looper.prepare();
builder.setTitle("Warning...!");
builder.create();
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setPositiveButton("More Details", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent= new Intent(MyActivity.this,Report.class);
intent.putExtra("error", throwable);
startActivity(intent);
}
});
builder.setMessage(throwable.getMessage());
builder.show();
Looper.loop();
}
}.start();
}
});
}
}
答案 0 :(得分:0)
您需要更改此行
startActivity(intent);
通过
context.startActivity(intent);
答案 1 :(得分:0)
根据我的搜索结果,您似乎无法从Activity
开始UncaughtExceptionHandler
。您可以执行的最大操作是显示Toast
消息。
Toast.makeText(app, "Some message", Toast.LENGTH_SHORT).show();
答案 2 :(得分:-1)
此代码与我合作正常。
注意:在我定义的未捕获异常代码后,2 seconds
将加载新活动。
将下面的代码放在您的onCreate Activity of Activity
中Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(){
@Override
public void uncaughtException(Thread thread, Throwable ex) {
AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000, intent);
System.exit(2);
startActivity(new Intent(CurrentActivity.this,TargetActivity.class));
}
});
如果您对此有任何疑问,请告诉我!!