Getting a lot of crashes from android youtube player api

微笑、不失礼 提交于 2019-12-06 02:26:30

I reduced the bug occurrence by putting youtube calls (like youtubePlayer.loadVideo(), cueVideo(), getCurrentTimeMillis() etc.) in a try catch block and catch the IllegalStateException exception then reinitialize youtube player.

To create a new instance of the YoutubePlayer just call the initialize() method in the catch block.

Example:

 if (youtubePlayer != null) {
        try {
            youtubePlayer.loadVideo(videoId);
        } catch (IllegalStateException e) {
            initialize(API_KEY, this);
        }
    }

but the bug still occurred , I worked around it by catching these exceptions and restart activity. This uncaught exceptions and to catch them you need to use UncaughtExceptionHandler

example :

 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);
                    }
                };

The android YouTube Player API is not stable, there are known bugs in it. The team from YouTube said that they will release a new version of the library.

For now, the best solution I have found is to build my own library.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!