2014-05-13 84 views
1

嗨我正在处理一个第三方库,它有时会出错并导致重新启动活动。有没有一种方法可以告诉活动何时从崩溃中重新启动?我尝试使用这样的未捕获的异常处理程序,但它没有被触发。当一个活动从崩溃中重新启动时捕获

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { 
     @Override 
     public void uncaughtException(Thread thread, Throwable throwable) { 
      Log.d("un", "caught"); 
     } 
    }); 
+0

屏蔽错误永远是一个坏主意。请图书馆的作者解决这些错误或自己修复它们。 – Karakuri

回答

1

写这样

Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this,YOURCURRENTCLASSNAME.class)); 

而且使用这个类亲爱的。我也用这个

public class MyExceptionHandler implements 
     java.lang.Thread.UncaughtExceptionHandler { 
    private final Context myContext; 
    private final Class<?> myActivityClass; 

    public MyExceptionHandler(Context context, Class<?> c) { 

     myContext = context; 
     myActivityClass = c; 
    } 

    public void uncaughtException(Thread thread, Throwable exception) { 

     StringWriter stackTrace = new StringWriter(); 
     exception.printStackTrace(new PrintWriter(stackTrace)); 
     System.err.println(stackTrace);// You can use LogCat too 
     Intent intent = new Intent(myContext, myActivityClass); 
     String s = stackTrace.toString(); 
     // you can use this String to know what caused the exception and in 
     // which Activity 
     intent.putExtra("uncaughtException", 
       "Exception is: " + stackTrace.toString()); 
     intent.putExtra("stacktrace", s); 
     myContext.startActivity(intent); 
     // for restarting the Activity 
//  Process.killProcess(Process.myPid()); 
     System.out.println("comingggggggggggggggggg in crashhhhhhhhhhhhhhhhhhhh and restrttttttttttttt autometically "); 
     Intent i = myContext.getPackageManager().getLaunchIntentForPackage(myContext.getPackageName()); 
     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     i.addCategory(Intent.CATEGORY_HOME); 
     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); 
     i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     myContext.startActivity(i); 
     System.exit(0); 
    } 
} 
+0

是否有一种方法可以重写此消息,并将消息传递给默认日志猫,并显示错误颜色? – user1634451

0

或者,如果你正在寻找工作,出的现成的解决方案,你可以使用bug跟踪服务,如CrashlyticsCrittercism。他们都提供了一种方法来了解当前运行是否发生在碰撞后。

Crashlytics

Crashlytics.getInstance().setListener(new CrashlyticsListener() { 
    @Override 
    public void crashlyticsDidDetectCrashDuringPreviousExecution() { 
     // if this method is called, it means that a crash occurred 
     // in the previous run 
     didCrashOnLastLoad = true; 
    } 
}); 

Crittercismsource

CritterCallback cb = new CritterCallback() { 
    @Override public void onCritterDataReceived(CritterUserData userData) { 
     boolean crashedOnLastLoad = userData.crashedOnLastLoad(); 
     // ...do something with crashedOnLastLoad 
    } 
}; 

CritterUserDataRequest request = new CritterUserDataRequest(cb) 
           .requestDidCrashOnLastLoad(); 

// Fire off the request. 
request.makeRequest(); 
相关问题