2014-12-04 133 views
0

我在我的Android應用程序中使用YouTube API。一切初始化都很好,點擊播放視頻,但當我選擇以全屏模式播放視頻時,它只是強制手機旋轉並播放視頻1秒,然後停止。當我再次嘗試播放視頻時,它會重複相同的操作:播放1秒然後停止播放。我會很感激你的任何幫助修復這個錯誤。我有一個想法,聽衆有些問題,但我沒有提出解決方案。我張貼下面的代碼(主要是片段,其與YouTube播放器連接...)如果你需要任何細節,歡迎您來問...當設備旋轉時,YouTube播放器無法播放

public class ItemScreen extends ActionBarActivity implements BaseSliderView.OnSliderClickListener, YouTubePlayer.OnInitializedListener { 

public String VIDEO_ID; 
private SliderLayout mDemoSlider; 
private ClickableItem ci; 
private RatingBar rb; 
private SharedPreferences sp; 
private String location; 
private int position; 
private TextView rating_text; 
private double votes, voters; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.item_screen); 
    //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
    mDemoSlider = (SliderLayout) findViewById(R.id.slider); 
    TextView work_hours = (TextView) findViewById(R.id.work_hours); 
    TextView address = (TextView) findViewById(R.id.address); 
    TextView description = (TextView) findViewById(R.id.description); 
    rating_text = (TextView) findViewById(R.id.rating_text); 
    ImageButton pin = (ImageButton) findViewById(R.id.pin); 
    final ImageButton number = (ImageButton) findViewById(R.id.number); 
    final ImageButton email = (ImageButton) findViewById(R.id.email); 
    rb = (RatingBar) findViewById(R.id.ratingBar); 
    View divider = (View) findViewById(R.id.divider4); 
    View otherDivider = (View) findViewById(R.id.divider3); 

    FrameLayout frameLayout = (FrameLayout) findViewById(R.id.frame_layout); 
    //YouTubePlayerSupportFragment youTubePlayerFragment = (YouTubePlayerSupportFragment) getSupportFragmentManager().findFragmentById(R.id.youtube_fragment); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
    Intent i = getIntent(); 
    position = i.getIntExtra("position", 0); 
    location = i.getStringExtra("location"); 
    if (location.equals("events")) { 
     number.setVisibility(View.GONE); 
     email.setVisibility(View.GONE); 
    } 
    if (location.equals("events") || location.equals("cinema")) { 
     rb.setVisibility(View.GONE); 
     divider.setVisibility(View.GONE); 
    } 

    ci = new ClickableItem(); 
    DatabaseHandler db = new DatabaseHandler(this); 
    ci = db.getAllClickableItems(location).get(position); 
    db.closeDB(); 
    getSupportActionBar().setTitle(ci.getName()); 

    if (location.equals("cinema")) { 
     FragmentManager fragmentManager = getSupportFragmentManager(); 
     FragmentTransaction fragmentTransaction = fragmentManager 
       .beginTransaction(); 

     YouTubePlayerSupportFragment fragment = new YouTubePlayerSupportFragment(); 
     fragmentTransaction.add(R.id.frame_layout, fragment); 
     fragmentTransaction.commit(); 
     fragment.initialize(DeveloperKey.DEVELOPER_KEY, this); 
     VIDEO_ID = ci.getTrailer(); 
     VIDEO_ID = getYoutubeVideoId(VIDEO_ID); 
    } else { 
     frameLayout.setVisibility(View.GONE); 
     //otherDivider. 
    } 

    work_hours.setText(ci.getWork_hours()); 
    address.setText(ci.getAddress()); 
    description.setText(ci.getDescription()); 
    String foto_links = ci.getFoto_links(); 
    HashMap<String, String> url_maps = new HashMap<String, String>(); 
    String url, name_foto = ci.getName(); 
    int pos; 
    if (!foto_links.contains(",")) 
     url_maps.put(name_foto, encode_url(foto_links, location)); 
    else 
     while (!foto_links.equals("")) { 
      pos = foto_links.indexOf(','); 
      url = foto_links.substring(0, pos); 
      url_maps.put(name_foto, encode_url(url, location)); 
      foto_links = foto_links.replace(url, ""); 
      foto_links = foto_links.substring(1); 
      name_foto += " "; 
      if (!foto_links.contains(",")) { 
       url_maps.put(name_foto, encode_url(foto_links, location)); 
       break; 
      } 
     } 

    for (String name : url_maps.keySet()) { 
     TextSliderView textSliderView = new TextSliderView(this); 
     textSliderView 
       .description(name) 
       .image(url_maps.get(name)) 
       .setScaleType(BaseSliderView.ScaleType.Fit) 
       .setOnSliderClickListener(this); 
     textSliderView.getBundle() 
       .putString("extra", name); 
     mDemoSlider.addSlider(textSliderView); 
    } 
    mDemoSlider.setPresetTransformer(SliderLayout.Transformer.Default); 
    mDemoSlider.setPresetIndicator(SliderLayout.PresetIndicators.Center_Top); 
    mDemoSlider.setCustomAnimation(new DescriptionAnimation()); 
    mDemoSlider.setDuration(4000); 
    sp = getSharedPreferences("MyPrefs", MODE_PRIVATE); 
    if (!sp.getBoolean(ci.getName(), true)) { 
     rb.setRating(sp.getFloat(ci.getName() + " ", 0)); 
     votes = ci.getVotes() + Math.round(sp.getFloat(ci.getName() + " ", 0)); 
     voters = ci.getVoters() + 1; 
     rating_text.setText("Dabartinis reitingas: " + String.format("%2.02f", votes/voters)); 
    } else if (ci.getVoters() != 0) { 
     votes = ci.getVotes(); 
     voters = ci.getVoters(); 
     rating_text.setText("Dabartinis reitingas: " + String.format("%2.02f", votes/voters)); 
    } else { 
     voters = votes = 0; 
    } 

    rb.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { 
     @Override 
     public void onRatingChanged(RatingBar ratingBar, final float rating, boolean fromUser) { 
      if (rating != 0) 
       if (sp.getBoolean(ci.getName(), true)) { 
        if (checkInternetConnection()) { 
         RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); 
         StringRequest postRequest = new StringRequest(Request.Method.POST, "SERVER", 
           new Response.Listener<String>() { 
            @Override 
            public void onResponse(String response) { 
            } 
           }, 
           new Response.ErrorListener() { 
            @Override 
            public void onErrorResponse(VolleyError error) { 
             Log.d("Error.Response", error.toString()); 
            } 
           } 
         ) { 
          @Override 
          protected Map<String, String> getParams() { 
           Map<String, String> params = new HashMap<String, String>(); 
           params.put("table", location); 
           params.put("name", ci.getName()); 
           params.put("vote", String.valueOf(Math.round(rating))); 
           return params; 
          } 
         }; 
         queue.add(postRequest); 
         Toast.makeText(getApplicationContext(), "Tavo balsas išsiųstas!", Toast.LENGTH_SHORT).show(); 
         SharedPreferences.Editor editor = sp.edit(); 
         editor.putBoolean(ci.getName(), false); 
         editor.putFloat(ci.getName() + " ", rating); 
         editor.commit(); 
         votes = ci.getVotes() + rating; 
         voters = ci.getVoters() + 1; 
         rating_text.setText("Dabartinis reitingas: " + String.format("%2.02f", votes/voters)); 
        } else { 
         rb.setRating(0); 
        } 
       } else { 
        rb.setRating(sp.getFloat(ci.getName() + " ", 0)); 
        Toast.makeText(getApplicationContext(), "Tu jau balsavai už šią vietą!", Toast.LENGTH_SHORT).show(); 
       } 
     } 
    }); 

    number.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      //number.setImageResource(R.drawable.telefonas_clicked); 
      Intent callIntent = new Intent(Intent.ACTION_CALL); 
      callIntent.setData(Uri.parse("tel:" + ci.getNumber())); 
      startActivity(callIntent); 
     } 
    }); 
    email.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      //email.setImageResource(R.drawable.laiskas_clicked); 
      Intent email = new Intent(Intent.ACTION_SEND); 
      email.putExtra(Intent.EXTRA_EMAIL, new String[]{ci.getEmail()}); 
      email.putExtra(Intent.EXTRA_SUBJECT, "Aš naudojuosi Miesto Meniu!"); 
      email.setType("message/rfc822"); 
      startActivity(Intent.createChooser(email, "Pasirinkite programėlę")); 

     } 
    }); 
    pin.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent i = new Intent(getApplicationContext(), Maps.class); 
      i.putExtra("location", location); 
      i.putExtra("position", position); 
      i.putExtra("one", true); 
      startActivity(i); 
     } 
    }); 
} 

@Override 
public void onSliderClick(BaseSliderView slider) { 
} 

private String encode_url(String url, String loc) { 
    Log.d("url tikras: ", url); 
    String nereikalinga = url.split("/")[url.split("/").length - 1]; 
    Log.d("nereikalinga: ", nereikalinga); 
    try { 
     Log.d("toks url: ", url.replace(nereikalinga, (URLEncoder.encode(nereikalinga, "UTF-8")))); 
     if (!loc.equals("events")) 
      return url.replace(nereikalinga, (URLEncoder.encode(nereikalinga, "UTF-8"))); 
    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } 
    return url; 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater menuInflater = getMenuInflater(); 
    menuInflater.inflate(R.menu.item_screen, menu); 
    return super.onCreateOptionsMenu(menu); 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
     case android.R.id.home: 
      onBackPressed(); 
      return true; 
     case R.id.share: 
      Intent emailIntent = new Intent(Intent.ACTION_SEND); 
      emailIntent.setData(Uri.parse("mailto:")); 
      emailIntent.setType("text/plain"); 
      emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Aš naudojuosi Miesto Meniu!"); 
      emailIntent.putExtra(Intent.EXTRA_TEXT, ci.getName() + "\n" + "\n" + 
        ci.getAddress() + "\n" + "\n" + ci.getWork_hours() + "\n" + "\n" + 
        ci.getDescription() + "\n" + "\n" + ci.getNumber() + "\n" + "\n" + 
        ci.getEmail()); 
      try { 
       startActivity(Intent.createChooser(emailIntent, "Pasirinkite programėlę")); 
      } catch (android.content.ActivityNotFoundException ex) { 
       Toast.makeText(ItemScreen.this, 
         "Klaida!", Toast.LENGTH_SHORT).show(); 
      } 
      break; 
    } 
    return super.onOptionsItemSelected(item); 
} 

private boolean checkInternetConnection() { 
    ConnectionDetector cd = new ConnectionDetector(this); 
    Boolean isInternetPresent = cd.isConnectingToInternet(); 
    if (!isInternetPresent) { 
     AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); 
     alertDialogBuilder 
       .setTitle("Nėra interneto ryšio!") 
       .setMessage("Programėlei reikalingas interneto ryšys, norint balsuoti") 
       .setCancelable(false) 
       .setPositiveButton("Gerai", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         //rb.setActivated(false); 
        } 
       }); 
     AlertDialog alertDialog = alertDialogBuilder.create(); 
     alertDialog.show(); 
     return false; 
    } 
    return true; 
} 

@Override 
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult result) { 
    Toast.makeText(this, "Klaida!", Toast.LENGTH_LONG).show(); 
} 


@Override 
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) { 

    player.setPlayerStateChangeListener(playerStateChangeListener); 
    player.setPlaybackEventListener(playbackEventListener); 

    if (!wasRestored) { 
     player.cueVideo(VIDEO_ID); 
    } 
} 

private YouTubePlayer.PlaybackEventListener playbackEventListener = new YouTubePlayer.PlaybackEventListener() { 

    @Override 
    public void onBuffering(boolean arg0) { 

    } 

    @Override 
    public void onPaused() { 

    } 

    @Override 
    public void onPlaying() { 

    } 

    @Override 
    public void onSeekTo(int arg0) { 

    } 

    @Override 
    public void onStopped() { 

    } 

}; 

private YouTubePlayer.PlayerStateChangeListener playerStateChangeListener = new YouTubePlayer.PlayerStateChangeListener() { 

    @Override 
    public void onAdStarted() { 

    } 

    @Override 
    public void onError(YouTubePlayer.ErrorReason arg0) { 

    } 

    @Override 
    public void onLoaded(String arg0) { 

    } 

    @Override 
    public void onLoading() { 
    } 

    @Override 
    public void onVideoEnded() { 

    } 

    @Override 
    public void onVideoStarted() { 

    } 
}; 

//@Override 

protected YouTubePlayer.Provider getYouTubePlayerProvider() { 
    return (YouTubePlayerSupportFragment) getSupportFragmentManager().findFragmentById(R.id.youtube_fragment); 
} 

public static String getYoutubeVideoId(String youtubeUrl) { 
    String video_id = ""; 
    if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http")) { 

     String expression = "^.*((youtu.be" + "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/; 
     CharSequence input = youtubeUrl; 
     Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); 
     Matcher matcher = pattern.matcher(input); 
     if (matcher.matches()) { 
      String groupIndex1 = matcher.group(7); 
      if (groupIndex1 != null && groupIndex1.length() == 11) 
       video_id = groupIndex1; 
     } 
    } 
    return video_id; 
} 
} 

那類佈局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
xmlns:custom="http://schemas.android.com/apk/res-auto" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" 
android:gravity="center" 
tools:context="com.daimajia.slider.demo.MainActivity"> 

<ScrollView 
    android:layout_width="match_parent" 
    android:layout_height="0dp" 
    android:layout_weight="1" 
    android:fillViewport="true" 
    android:background="@drawable/background"> 

    <!--android:margin="5dp"--> 

    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:padding="5dp" 
     android:id="@+id/relative_layout" 
     android:background="#4D000000"> 

     <com.daimajia.slider.library.SliderLayout 
      android:id="@+id/slider" 
      android:layout_width="match_parent" 
      custom:pager_animation="Default" 
      custom:indicator_visibility="visible" 
      custom:pager_animation_span="1100" 
      android:layout_height="200dp" /> 

     <TextView 
      android:id="@+id/address" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Konstitucijos pr. 7A, Vilnius" 
      android:textColor="#FFFFFF" 
      android:layout_below="@+id/slider" 
      android:layout_marginTop="15dp" /> 

     <ImageButton 
      android:id="@+id/pin" 
      android:layout_width="32dp" 
      android:layout_height="32dp" 
      android:layout_below="@+id/slider" 
      android:layout_alignParentRight="true" 
      android:layout_marginRight="5dp" 
      android:background="@drawable/pin" 
      android:layout_marginTop="5dp" /> 

     <View 
      android:id="@+id/divider1" 
      android:layout_width="match_parent" 
      android:layout_height="1dp" 
      android:background="#433b39" 
      android:layout_below="@id/address" 
      android:layout_marginTop="10dp" /> 

     <TextView 
      android:id="@+id/work_hours" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_below="@+id/divider1" 
      android:text="I - VI 10:00 - 21:00, VII 10:00 - 20:00" 
      android:textColor="#FFFFFF" 
      android:layout_marginTop="10dp" /> 

     <View 
      android:id="@+id/divider2" 
      android:layout_width="match_parent" 
      android:layout_height="1dp" 
      android:background="#433b39" 
      android:layout_below="@id/work_hours" 
      android:layout_marginTop="10dp" /> 

     <TextView 
      android:id="@+id/description" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_below="@+id/divider2" 
      android:layout_marginTop="10dp" 
      android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." 
      android:textColor="#FFFFFF" /> 

     <FrameLayout 
      android:id="@+id/frame_layout" 
      android:layout_below="@+id/description" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content"> 

      <fragment 
       android:name="com.google.android.youtube.player.YouTubePlayerFragment" 
       android:id="@+id/youtube_fragment" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" /> 
     </FrameLayout> 

     <View 
      android:id="@+id/divider3" 
      android:layout_width="match_parent" 
      android:layout_height="1dp" 
      android:background="#575350" 
      android:layout_below="@id/frame_layout" 
      android:layout_marginTop="10dp" /> 

     <RelativeLayout 
      android:layout_below="@+id/divider3" 
      android:layout_width="match_parent" 
      android:id="@+id/rl" 
      android:layout_height="wrap_content"> 

      <RatingBar 
       android:id="@+id/ratingBar" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_centerInParent="true" 
       android:numStars="5" 
       android:stepSize="1.0" 
       android:rating="0" /> 

      <TextView 
       android:layout_width="match_parent" 
       android:id="@+id/rating_text" 
       android:layout_below="@+id/ratingBar" 
       android:layout_height="wrap_content" 
       android:gravity="center"/> 

     </RelativeLayout> 

     <View 
      android:id="@+id/divider4" 
      android:layout_width="match_parent" 
      android:layout_height="1dp" 
      android:background="#575350" 
      android:layout_below="@id/rl" /> 

     <LinearLayout 
      android:layout_below="@id/divider4" 
      android:layout_height="wrap_content" 
      android:layout_width="match_parent" 
      android:orientation="horizontal" 
      android:layout_margin="5dp" 
      android:clickable="true"> 

      <TextView 
       android:layout_width="0dp" 
       android:layout_height="wrap_content" 
       android:layout_weight="1.0" 
       android:text="" /> 

      <ImageButton 
       android:id="@+id/number" 
       android:layout_height="wrap_content" 
       android:layout_width="wrap_content" 
       android:background="@drawable/phone" /> 

      <TextView 
       android:layout_width="0dp" 
       android:layout_height="wrap_content" 
       android:layout_weight="1.0" 
       android:text="" /> 

      <TextView 
       android:layout_width="0dp" 
       android:layout_height="wrap_content" 
       android:layout_weight="1.0" 
       android:text="" /> 

      <ImageButton 
       android:id="@+id/email" 
       android:layout_height="wrap_content" 
       android:layout_width="wrap_content" 
       android:background="@drawable/mail" /> 

      <TextView 
       android:layout_width="0dp" 
       android:layout_height="wrap_content" 
       android:layout_weight="1.0" 
       android:text="" /> 
     </LinearLayout> 

    </RelativeLayout> 

</ScrollView> 

<com.daimajia.slider.library.Indicators.PagerIndicator 
    android:id="@+id/custom_indicator2" 
    style="@style/AndroidImageSlider_Corner_Oval_Orange" 
    android:layout_marginBottom="10dp" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 

<com.daimajia.slider.library.Indicators.PagerIndicator 
    android:id="@+id/custom_indicator" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:gravity="center" 
    custom:selected_color="#0095BF" 
    custom:unselected_color="#55333333" 
    custom:shape="oval" 
    custom:selected_padding_left="5dp" 
    custom:selected_padding_right="5dp" 
    custom:unselected_padding_left="5dp" 
    custom:unselected_padding_right="5dp" 
    custom:selected_width="6dp" 
    custom:selected_height="6dp" 
    custom:unselected_width="6dp" 
    custom:unselected_height="6dp"/> 

編輯:我發現,它帶有在日誌中的錯誤: 12-04 15:23:33.800 6836-6836 W/YouTubeAndroidPlayerAPI:YouTube視頻的playbac k由於玩家之上未經授權的覆蓋而停止。 YouTubePlayerView不包含在其祖先android.widget.ScrollView {434fe9e0 VFED.V .. ....... D 0,0-1794,861}內。祖先的邊緣與YouTubePlayerView的邊緣之間的距離是:left:15,top:-410,right:15,bottom:279(這些都應該是正數)。 YouTube播放器播放的位置是電影院。 我相信,它與setVisibility()屬性有關,其中元素被迫與YouTube片段重疊。

enter image description here

回答

0

不能切割或overaly YouTube觀看的任何部分。確保Youtube視圖的大小是< =它的容器的大小。

相關問題