我通过将 youtube 调用(如 youtubePlayer.loadVideo()、cueVideo()、getCurrentTimeMillis() 等)放在 try catch 块中并捕获 IllegalStateException 异常,然后重新初始化 youtube 播放器来减少错误的发生。
要创建 YoutubePlayer 的新实例,只需调用 catch 块中的initialize() 方法。
Example:
if (youtubePlayer != null) {
try {
youtubePlayer.loadVideo(videoId);
} catch (IllegalStateException e) {
initialize(API_KEY, this);
}
}
但错误仍然发生,我通过捕获这些异常并重新启动活动来解决它。这种未捕获的异常要捕获它们,您需要使用 UncaughtExceptionHandler
例子 :
private Thread.UncaughtExceptionHandler defaultUEH;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
// setup handler for uncaught exception
Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}
private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler =
new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
Log.e(TAG, "uncaughtException: ", ex);
PendingIntent myActivity = PendingIntent.getActivity(getApplicationContext(),
192837, new Intent(getApplicationContext(), MainActivity.class),
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager;
alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
15000, myActivity );
System.exit(2);
// re-throw critical exception further to the os (important)
defaultUEH.uncaughtException(thread, ex);
}
};