An error occurred while initializing the youtube player

I have an android app, which allows to play youtube video. I am using the latest YouTube API (1.2.1). I try it on a several devices within android version 4.0.4, 4.3, 4.4.4 or 5.0 and it works perf...

I have an android app, which allows to play youtube video. I am using the latest YouTube API (1.2.1). I try it on a several devices within android version 4.0.4, 4.3, 4.4.4 or 5.0 and it works perfect (on every device is YouTube app version 10.-. But on one device, where is android 4.0.4 and YouTube app version 4.4.11 it does not work and get an error «An error occurred while initializing YouTube player». In documentation is written, that the minimal required version of YouTube app is 4.2.16. So I don’t know, where is the problem.

Does somebody have an idea, what is wrong or how can I fix it?

Thanks a lot…

asked Mar 18, 2015 at 22:25

pojta's user avatar

2

This issues coming in Android 11 and above version, due to Package visibility filtering

The limited app visibility affects the return results of methods that give information about other apps, such as queryIntentActivities(), getPackageInfo(), and getInstalledApplications(). The limited visibility also affects explicit interactions with other apps, such as starting another app’s service.

For more info : https://developer.android.com/training/package-visibility

Add the below lines of code into your AndroidManifest.xml file

<queries>
   <intent>
      <action android:name="com.google.android.youtube.api.service.START" />
   </intent>
</queries>

Bhavesh Jabuvani's user avatar

answered Feb 23, 2021 at 9:35

Bilal Tariq's user avatar

Bilal TariqBilal Tariq

5793 silver badges6 bronze badges

5

Update your Android youtube app to the latest version and it will work for Sure!!

answered May 31, 2016 at 18:38

Sourav Nanda's user avatar

Sourav NandaSourav Nanda

1,7311 gold badge10 silver badges11 bronze badges

0

I would never have thought to look in that location for the settings. It worked just as you said.

Here are the instructions for that less knowledge of the settings.

First, you need to go Settings -> battery -> app launch -> YouTube.

Now make disable the option manage automatically.

After disabling the above option, a popup will be shown.

Now make enable the option Secondary Launch (can be launched by other apps)

Parth Patel's user avatar

Parth Patel

9552 gold badges11 silver badges28 bronze badges

answered May 31, 2019 at 12:40

Faiyyaz's user avatar

If someone still getting this error then,

The problem is in the layout file, may be you defined the fixed height and width :

<com.google.android.youtube.player.YouTubePlayerView
    android:layout_width="123dp"
    android:layout_height="123dp" />

Replace height and width with «wrap_content» :

<com.google.android.youtube.player.YouTubePlayerView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

answered Jan 12, 2022 at 18:50

Jay Parmar's user avatar

1

I replaced targetSdkVersion =30 to targetSdkVersion =26 and it’s worked for me

apply plugin: 'com.android.application'

android {
    compileSdkVersion 30`enter code here`
    defaultConfig {
        applicationId "com.loopwiki.youtubeplayerexample"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:design:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation files('libs/YouTubeAndroidPlayerApi.jar')
}

answered Jun 18, 2021 at 19:32

rajashree's user avatar

1

I have a Fragment containing a YouTubePlayerSupportFragment. This fragment is inside a ViewPager.

The player works fine on my Galaxy S3 Android phone (4.3 / API 18) and on my VM (4.3 / API 18). But on every other phones i’ve tried, the player shows a An error occurred while initializing YouTube player message and throw a onInitializationFailure with an UNKNOWN_ERROR reason.

I’ve checked the LogCat and there is absolutly no other error/warning, from my app or from youtube.

It didnt work on the following devices:

  • Android 4.2.1 — Youtube 10.18.55
  • Android 4.4.2 — Youtube 10.18.55
  • Android 5.1 — Youtube above requirement

I have absolutely no idea why it worked on some and why it didn’t on others.

Here is the code of the Fragment:

    public class RoomFragmentVideo extends PlugFragment implements
    YouTubePlayer.OnInitializedListener, YouTubePlayer.PlayerStateChangeListener {
            private static String CLASS_DBG_NAME = "RoomFragmentVideo";

            private static final int RECOVERY_DIALOG_REQUEST = 1;

            private YouTubePlayerSupportFragment youTubePlayer ;
            private int playerInitialized;
            private YouTubePlayer player;

            static PlugFragment init(Bundle args) {
                     RoomFragmentVideo roomFrag = new RoomFragmentVideo();
                     // Supply val input as an argument.
                     roomFrag.setArguments(args);
                     Log.d(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - ","Created with args Room: "  + ((String)args.get(RoomFragmentChat.ARG_ROOM)));
                     return roomFrag;
            }

            @Override
            public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             thisActivity = (AppCompatActivity) this.getActivity();
            }

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
             Bundle savedInstanceState) {
                     View rootview = inflater.inflate(R.layout.fragment_roomvideo, container,false);
                     youTubePlayer = YouTubePlayerSupportFragment.newInstance();
                     FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
                     transaction.add(R.id.youtube_fragment, youTubePlayer).commit();
                     youTubePlayer.initialize(YouTubeDeveloperKey.DEVELOPER_KEY, this);
                     return rootview;

            }

            protected YouTubePlayer.Provider getYouTubePlayerProvider() {
                return youTubePlayer;
            }

            @Override
            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                if (requestCode == RECOVERY_DIALOG_REQUEST) {
                  getYouTubePlayerProvider().initialize(YouTubeDeveloperKey.DEVELOPER_KEY, this);
                }
            }         

            @Override
            public void onInitializationFailure(YouTubePlayer.Provider provider,
                          YouTubeInitializationResult errorReason) {
                    if (errorReason.isUserRecoverableError()) {
                          errorReason.getErrorDialog(this.getActivity(), 1).show();
                          Log.e(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - YouTube" ,"[Recoverable] Reason : " + errorReason.toString());
                    }
                    else {
                            //String errorMessage = String.format(getString(R.string.error_player), errorReason.toString());
                            String errorMessage = "Video couldnt load";
                            Toast.makeText(this.getActivity(), errorMessage, Toast.LENGTH_LONG).show();
                            Log.e(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - YouTube" ,"[Unrecoverable] Reason : " + errorReason.toString() + " Message: " + errorMessage);
                            playerInitialized = -1;
                    }

            }

            @Override
            public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
                          boolean wasRestored) {
                            this.player = player;
                            player.setPlayerStyle(PlayerStyle.CHROMELESS);
                            player.loadVideo(this.videoID);
                            playerInitialized = 1;
            }

            @Override
            public void onPause(){
                    super.onPause();
                    Log.v(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - " , "onPause");
            }

            @Override
            public void onResume(){
                    super.onResume();
                    Log.v(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - " , "onResume");
            }

            @Override
            public void onStop(){
                    super.onStop();
                    player = null;
                    playerInitialized = -2;
                    Log.v(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - " , "onStop");
            }

            @Override
            public void setUserVisibleHint (boolean isVisibleToUser){
                    super.setUserVisibleHint(isVisibleToUser);
                    if(isVisibleToUser){
                            this.resume();
                    }
                    Log.v(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - " , "setUserVisibleHint, status: " + isVisibleToUser);
            }

            @Override
            public void onAdStarted() {
                    return;
            }

            @Override
            public void onError(ErrorReason arg0) {
                    Log.e(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - " +"YoutubePlayer", arg0.name());
                    Toast.makeText(thisActivity, "YoutubePlayer error: " + arg0.name(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onLoaded(String arg0) {
                    return;
            }

            @Override
            public void onLoading() {
                    return;
            }

            @Override
            public void onVideoEnded() {
                    return;
            }

            @Override
            public void onVideoStarted() {
                    return;

            }
    }

And here is the XML:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

       <FrameLayout
            android:id="@+id/youtube_fragment"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:visibility="visible" />

    </LinearLayout>

What am I doing wrong ?

Thanks a lot !


The problem was in fact proguard. Here is what i added to the proguard-project.txt file:

# keep youtube / google
-keep class com.google.api.services.** { *; }
-keep class com.google.android.youtube.player.** { *; }
# Needed by google-api-client to keep generic types and @Key annotations accessed via reflection
-keepclassmembers class * {
  @com.google.api.client.util.Key <fields>;
}

Я использую API Youtube, чтобы иметь простой playerView в своем приложении. Я сделал то, что сказал API, но я продолжаю получать сообщение «приложение остановлено». Я не знаю точную английскую фразу, так как пользуюсь корейским телефоном. Надеюсь, это правильная фраза на английском языке.

Я поместил Youtubeandroidplayerapi.jar в библиотеки и построил путь, а ненужные компоненты были в библиотеке.

Вот Menu.java.

package com.hobak.sci;

import com.hobak.sci.DeveloperKey;
import com.hobak.sci.R;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
import android.os.Bundle;

public class Menu extends YouTubeBaseActivity implements
    YouTubePlayer.OnInitializedListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu);

        YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
    youTubeView.initialize(DeveloperKey.DEVELOPER_KEY, this);
    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider,
        YouTubePlayer player, boolean wasRestored) {
    if (!wasRestored) {
        player.cueVideo("2LHv1FPd1Ec");
    }
}

protected YouTubePlayer.Provider getYouTubePlayerProvider() {
    return (YouTubePlayerView) findViewById(R.id.youtube_view);
}

@Override
public void onInitializationFailure(Provider arg0,
        YouTubeInitializationResult arg1) {
    // TODO Auto-generated method stub

}

}

а вот мой xml файл

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFACD"
    android:orientation="vertical" >


  <com.google.android.youtube.player.YouTubePlayerView
    android:id="@+id/youtube_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />



</LinearLayout>

а вот мой логкэт

03-17 15:55:51.260: E/AndroidRuntime(5277): FATAL EXCEPTION: main
03-17 15:55:51.260: E/AndroidRuntime(5277): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hobak.sci/com.hobak.sci.Menu}: java.lang.SecurityException: Not allowed to bind to service Intent { act=com.google.android.youtube.api.service.START }
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1961)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1986)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.access$600(ActivityThread.java:128)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1152)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.os.Looper.loop(Looper.java:137)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.main(ActivityThread.java:4453)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at java.lang.reflect.Method.invokeNative(Native Method)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at java.lang.reflect.Method.invoke(Method.java:511)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at dalvik.system.NativeStart.main(Native Method)
03-17 15:55:51.260: E/AndroidRuntime(5277): Caused by: java.lang.SecurityException: Not allowed to bind to service Intent { act=com.google.android.youtube.api.service.START }
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ContextImpl.bindService(ContextImpl.java:1164)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.content.ContextWrapper.bindService(ContextWrapper.java:370)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.internal.r.e(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.YouTubePlayerView.a(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.YouTubeBaseActivity$a.a(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.YouTubePlayerView.initialize(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.hobak.sci.Menu.onCreate(Menu.java:21)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.Activity.performCreate(Activity.java:4467)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1925)
03-17 15:55:51.260: E/AndroidRuntime(5277):     ... 11 more

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

Я использую API Youtube, чтобы иметь простой плеер в моем приложении. Я сделал то, что сказал API, но я продолжаю получать сообщение «приложение остановлено». Я не знаю точно английскую фразу, так как я использую корейский телефон. Надеюсь, что правильная фраза на английском.

Я поместил Youtubeandroidplayerapi.jar в libs и построил путь и имел ненужные компоненты в библиотеке.

Вот Menu.java.

package com.hobak.sci;

import com.hobak.sci.DeveloperKey;
import com.hobak.sci.R;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
import android.os.Bundle;

public class Menu extends YouTubeBaseActivity implements
    YouTubePlayer.OnInitializedListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu);

        YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
    youTubeView.initialize(DeveloperKey.DEVELOPER_KEY, this);
    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider,
        YouTubePlayer player, boolean wasRestored) {
    if (!wasRestored) {
        player.cueVideo("2LHv1FPd1Ec");
    }
}

protected YouTubePlayer.Provider getYouTubePlayerProvider() {
    return (YouTubePlayerView) findViewById(R.id.youtube_view);
}

@Override
public void onInitializationFailure(Provider arg0,
        YouTubeInitializationResult arg1) {
    // TODO Auto-generated method stub

}

}

и вот мой xml файл

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFACD"
    android:orientation="vertical" >


  <com.google.android.youtube.player.YouTubePlayerView
    android:id="@+id/youtube_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />



</LinearLayout>

и вот мой logcat

03-17 15:55:51.260: E/AndroidRuntime(5277): FATAL EXCEPTION: main
03-17 15:55:51.260: E/AndroidRuntime(5277): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hobak.sci/com.hobak.sci.Menu}: java.lang.SecurityException: Not allowed to bind to service Intent { act=com.google.android.youtube.api.service.START }
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1961)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1986)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.access$600(ActivityThread.java:128)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1152)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.os.Looper.loop(Looper.java:137)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.main(ActivityThread.java:4453)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at java.lang.reflect.Method.invokeNative(Native Method)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at java.lang.reflect.Method.invoke(Method.java:511)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at dalvik.system.NativeStart.main(Native Method)
03-17 15:55:51.260: E/AndroidRuntime(5277): Caused by: java.lang.SecurityException: Not allowed to bind to service Intent { act=com.google.android.youtube.api.service.START }
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ContextImpl.bindService(ContextImpl.java:1164)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.content.ContextWrapper.bindService(ContextWrapper.java:370)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.internal.r.e(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.YouTubePlayerView.a(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.YouTubeBaseActivity$a.a(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.google.android.youtube.player.YouTubePlayerView.initialize(Unknown Source)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at com.hobak.sci.Menu.onCreate(Menu.java:21)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.Activity.performCreate(Activity.java:4467)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-17 15:55:51.260: E/AndroidRuntime(5277):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1925)
03-17 15:55:51.260: E/AndroidRuntime(5277):     ... 11 more

4b9b3361

Ответ 1

У меня была эта проблема. Затем я добавил

<uses-permission android:name="android.permission.INTERNET"/> в тег AndroidManifest.xml в теге <manifest>. После этого приложение отлично работало.

Ответ 2

Я исправил эту проблему, выполнив следующие шаги:

  • Очистить проект, а затем перестроить проект
  • Запустите приложение на устройстве с приложением Youtube с версией выше 4.2.16.

Ответ 3

возможно, это похоже на проблему с ключом разработчика.
образец ключа DEVELOPER_KEY, который находится в DeveloperKey.java, не будет работать.
сначала зарегистрируйте новый ключ разработчика. (https://code.google.com/apis/console)
затем замените это на действительный ключ.

Ответ 4

щелкните правой кнопкой мыши по проекту, перейдите в свойства- > java, встроенный в path- > libraries- > Добавьте библиотеку и добавьте туда файл jar, а затем он будет работать

если вы хотите использовать YouTube-видео в своем приложении, ваше устройство должно содержать приложение youtube, иначе оно не будет работать.

Ответ 5

Просто обновите приложение youtube до последней версии вашего телефона, и оно будет работать отлично

Ответ 6

Помимо добавления <uses-permission android:name="android.permission.INTERNET" /> в AndroidManifest.xml, вы должны иметь приложение youtube на устройстве/эмуляторе. Если вы хотите получить его на эмуляторе, отмените это:

https://play.google.com/store/apps/details?id=com.google.android.youtube&hl=en
(Вы можете получить apk с http://apps.evozi.com/apk-downloader/?id=com.google.android.youtube)

Ответ 7

Если проигрыватель не работает в Google Glass

Когда проигрыватель youtube терпит неудачу, параметр arg1 YouTubeInitializationResult, переданный методу сбоя, содержит информацию о том, почему проигрыватель потерпел неудачу. Я просто поджарил его, как вы можете видеть в приведенном выше коде. Я получил распечатку SERVIVE_MISSING в тосте. Я нашел список возможных возвращаемых значений на веб-сайте разработчика Google, и причиной ошибки SERVICE_MISSING является то, что служба API YouTube отсутствует на устройстве, Эта служба является частью стандартного приложения YouTube, которое Google распространяет с помощью Android, но, видимо, еще не добавило его в стакан. Чтобы устранить проблему, вы можете загрузить приложение для загрузки сервисов. Невозможно запустить приложение YouTube и смотреть видео с него, к сожалению, поскольку оно было написано для телефонов Android и не имеет голосового триггера/карты временной шкалы.

Его можно загрузить из здесь, или он загружен здесь: com.google.android.youtube-5.2.27.apk

Просто добавьте это с помощью:

adb install com.google.android.youtube-5.2.27.apk

Это устанавливает приложение YouTube на стекле. Теперь видео должно работать!

взято из: http://www.eg.bucknell.edu/~jpk017/doku.php?id=wiki:yt

Ответ 8

У меня была эта проблема в моей сборке релизов, но она работала после добавления этого в proguard

-keepclassmembers class fqcn.of.javascript.interface.for.webview {
       public *;
   }

Ответ 9

У меня была такая же проблема, так как после поиска и поиска в Google я получил ответ: —

           for youtube player you must have youtube app enabled and still if not work then update youtube to the latest version.

он будет работать тогда.

Я проверил LogCat, и никаких других ошибок / предупреждений в моем приложении или на YouTube нет.

Он не работал на следующих устройствах:

  • Android 4.2.1 — Youtube 10.18.55
  • Android 4.4.2 — Youtube 10.18.55
  • Android 5.1 — Youtube выше требования

Я понятия не имею, почему это сработало на одних и почему не на других.

Вот код фрагмента:

    public class RoomFragmentVideo extends PlugFragment implements
    YouTubePlayer.OnInitializedListener, YouTubePlayer.PlayerStateChangeListener {
            private static String CLASS_DBG_NAME = "RoomFragmentVideo";

            private static final int RECOVERY_DIALOG_REQUEST = 1;

            private YouTubePlayerSupportFragment youTubePlayer ;
            private int playerInitialized;
            private YouTubePlayer player;

            static PlugFragment init(Bundle args) {
                     RoomFragmentVideo roomFrag = new RoomFragmentVideo();
                     // Supply val input as an argument.
                     roomFrag.setArguments(args);
                     Log.d(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - ","Created with args Room: "  + ((String)args.get(RoomFragmentChat.ARG_ROOM)));
                     return roomFrag;
            }

            @Override
            public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             thisActivity = (AppCompatActivity) this.getActivity();
            }

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
             Bundle savedInstanceState) {
                     View rootview = inflater.inflate(R.layout.fragment_roomvideo, container,false);
                     youTubePlayer = YouTubePlayerSupportFragment.newInstance();
                     FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
                     transaction.add(R.id.youtube_fragment, youTubePlayer).commit();
                     youTubePlayer.initialize(YouTubeDeveloperKey.DEVELOPER_KEY, this);
                     return rootview;

            }

            protected YouTubePlayer.Provider getYouTubePlayerProvider() {
                return youTubePlayer;
            }

            @Override
            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                if (requestCode == RECOVERY_DIALOG_REQUEST) {
                  getYouTubePlayerProvider().initialize(YouTubeDeveloperKey.DEVELOPER_KEY, this);
                }
            }         

            @Override
            public void onInitializationFailure(YouTubePlayer.Provider provider,
                          YouTubeInitializationResult errorReason) {
                    if (errorReason.isUserRecoverableError()) {
                          errorReason.getErrorDialog(this.getActivity(), 1).show();
                          Log.e(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - YouTube" ,"[Recoverable] Reason : " + errorReason.toString());
                    }
                    else {
                            //String errorMessage = String.format(getString(R.string.error_player), errorReason.toString());
                            String errorMessage = "Video couldnt load";
                            Toast.makeText(this.getActivity(), errorMessage, Toast.LENGTH_LONG).show();
                            Log.e(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - YouTube" ,"[Unrecoverable] Reason : " + errorReason.toString() + " Message: " + errorMessage);
                            playerInitialized = -1; 
                    }

            }

            @Override
            public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
                          boolean wasRestored) {
                            this.player = player;
                            player.setPlayerStyle(PlayerStyle.CHROMELESS);
                            player.loadVideo(this.videoID);
                            playerInitialized = 1;
            }

            @Override
            public void onPause(){
                    super.onPause();
                    Log.v(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - " , "onPause");
            }

            @Override
            public void onResume(){
                    super.onResume();
                    Log.v(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - " , "onResume");
            }

            @Override
            public void onStop(){
                    super.onStop();
                    player = null;
                    playerInitialized = -2;
                    Log.v(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - " , "onStop");
            }

            @Override
            public void setUserVisibleHint (boolean isVisibleToUser){
                    super.setUserVisibleHint(isVisibleToUser);
                    if(isVisibleToUser){
                            this.resume();
                    }
                    Log.v(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - " , "setUserVisibleHint, status: " + isVisibleToUser);
            }

            @Override
            public void onAdStarted() {
                    return;                
            }

            @Override
            public void onError(ErrorReason arg0) {
                    Log.e(Constants.APP_DBG_LOG + CLASS_DBG_NAME + " - " +"YoutubePlayer", arg0.name());
                    Toast.makeText(thisActivity, "YoutubePlayer error: " + arg0.name(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onLoaded(String arg0) {
                    return;
            }

            @Override
            public void onLoading() {
                    return;
            }

            @Override
            public void onVideoEnded() {
                    return;
            }

            @Override
            public void onVideoStarted() {
                    return;

            }
    }

А вот XML:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

       <FrameLayout
            android:id="@+id/youtube_fragment"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:visibility="visible" />

    </LinearLayout>

Что я делаю не так ?

Большое спасибо !

Понравилась статья? Поделить с друзьями:
  • An error occurred while generating report the given key was not present in the dictionary
  • An error occurred while taking a snapshot invalid change tracker error code
  • An error occurred while taking a snapshot failed to quiesce the virtual machine
  • An error occurred while starting up the preloader
  • An error occurred while starting the task sequence 0x8007000f