2011-08-29 124 views
3

有沒有辦法讓我的程序我的應用程序在崩潰時自動重新啓動?我的應用程序只是一個簡單的媒體渲染應用程序,但它偶爾會崩潰(應該是)。這是可能嗎?謝謝。我的代碼看起來像這樣以編程方式崩潰後重新啓動應用程序 - Android

public void Play(){ if(mp != null) { 
      mp.reset(); 
      mp.release(); 
      mp = null; 
     } 
AudioRenderer mr = new AudioRenderer(); 
mp = mr.AudioRenderer(filePath); 
} 

private class AudioRenderer extends Activity { 
private MediaPlayer AudioRenderer(String filePath) {  
File location = new File(filePath); 
Uri path = Uri.fromFile(location); 
mp= MediaPlayer.create(this, path); 
} 
return mp 
} 
+2

我真的好奇......爲什麼應用程序應該崩潰? – Tenfour04

+1

爲什麼不只是將'應該[try]'的代碼包裝在try/catch中並正確處理錯誤? – CrackerJack9

+0

@ CrackerJack9這是不高效的。在某些情況下,例如,nullpointerexc,現在有辦法處理它。重新啓動後,並不好。 – alicanbatur

回答

10

這會爲你做這項工作。

How to start the automatically stopped android service?

我還是不明白爲什麼它應該崩潰。

您在上創建了未捕獲的異常

private Thread.UncaughtExceptionHandler onRuntimeError= new Thread.UncaughtExceptionHandler() { 
     public void uncaughtException(Thread thread, Throwable ex) { 
      //Try starting the Activity again 
    }; 

的處理UPDATE創建,你註冊一個處理程序未捕獲的異常

@Override 
    protected void onCreate() { 
     super.onCreate(); 
     Thread.setDefaultUncaughtExceptionHandler(onRuntimeError); 
    } 
+0

謝謝!我相信這會派上用場 – Sith

+1

如果這項工作可以考慮標記爲答案。 – Samuel

+1

這似乎是一種不可靠的方式來處理所有未被捕獲的錯誤,並且對用戶來說是一個令人困惑的體驗,他們只會看到應用程序突然再次導航到頂級活動。您是否有條件不想重新開始該活動?你確定要重新啓動所有未被捕獲的錯誤嗎?應用程序處於不一致狀態嗎?這對你的Activity堆棧有什麼影響?你記錄異常嗎?同意CrackerJack9:你應該包裝偶爾崩潰的特定代碼,並記錄下來。像這樣的全球處理程序通常是一個糟糕的想法。 –

1

我可能會晚點了很多,但我找到了2合1解決方案來解決您的問題。

public void doRestart() { 
    Intent mStartActivity = new Intent(context, LoginActivity.class); 
    int mPendingIntentId = 123456; 
    PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT); 
    AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent); 
    System.exit(0); 
} 

private void appInitialization() { 
    defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); 
    Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler); 
} 

//make crash report on ex.stackreport 
private Thread.UncaughtExceptionHandler defaultUEH; 
// handler listener 
private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() { 
    @Override 
    public void uncaughtException(Thread thread, Throwable ex) { 
     ex.printStackTrace(); 
     doRestart(); 
    } 
}; 



@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_index); 
    appInitialization(); 
相關問題