Вы просматриваете видеоролик в режиме просмотра веб-представления, когда я просматриваю веб-представление в сервисе (или процесс), то вы начинаете буферизацию с буфером видео и показывает «если воспроизведение не начинается в ближайшее время, попробуйте перезапустить ваше устройство».', если воспроизведение не начинается в ближайшее время, попробуйте перезагрузить устройство' при воспроизведении видео на YouTube в веб-браузере, и веб-просмотр находится в сервисе
Видео воспроизводится в HONOR NEM-L22 (OS-зефир), но не на других устройствах. Я пробовал в различных версиях ОС Android (lollipop, kitkat). В Sony C6802 только аудио воспроизведения видео не видно
Вот код
package com.appzcloud.youtube_webview;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@SuppressLint("SetJavaScriptEnabled")
public class AppopenService extends Service {
int screenwidth, screenheight;
private View myView;
LinearLayout bottm_layout;
RelativeLayout up_layout;
private WindowManager wm;
private WindowManager.LayoutParams params;
Utilities utils;
ScreenOrientationEnforcer screenChangelistner;
///////////////////////new variables/////////////////////////////////////////
private WebView mWebView;
Button playButton, close, backward, forward, shuffle, repeat;
SeekBar seekBar;
float totalVideoDuration;
final static int MAX = 1000;
int ErrorState = 0;
int PlayerStates;
List<String> videoList = new ArrayList<String>();
List<Integer> shuffleList = new ArrayList<Integer>();
List<Integer> listremove = new ArrayList<Integer>();
String selectedVideo = "";
int selectedVideoPosition = 0, selectedVideoPositionForSuffle = 0;
boolean repeatIsOn = false, shuffleisOn = false, genrater_random_number = false, videoisPlaying=true;
/*0 (ended) YT.PlayerState.ENDED
1 (playing) YT.PlayerState.PLAYING
2 (paused) YT.PlayerState.PAUSED
3 (buffering) YT.PlayerState.BUFFERING
5 (video cued). YT.PlayerState.CUED*/
@Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
utils = new Utilities();
Log.e("here we are","onCreate before inflater");
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
myView = inflater.inflate(R.layout.defaultpopup, null);
Log.e("here we are","onCreate after inflater myView"+ myView);
playButton = (Button) myView.findViewById(R.id.play);
close = (Button) myView.findViewById(R.id.cross);
backward = (Button) myView.findViewById(R.id.backward);
forward = (Button) myView.findViewById(R.id.forward);
shuffle = (Button) myView.findViewById(R.id.suffle);
repeat = (Button) myView.findViewById(R.id.repeat);
seekBar = (SeekBar) myView.findViewById(R.id.seekBar1);
seekBar.setMax(MAX);
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
screenwidth = windowManager.getDefaultDisplay().getWidth();
screenheight = windowManager.getDefaultDisplay().getHeight();
screenChangelistner = new ScreenOrientationEnforcer(this);
params = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER | Gravity.CENTER;
params.height=screenheight/2;
params.width=screenwidth-100;
videoList.add("f3hINqW-Z00");
videoList.add("G6Jpco8kKds");
videoList.add("PT2_F-1esPk");
videoList.add("bY_LRayav14");
videoList.add("WPwTPhFMm3k");
selectedVideo = videoList.get(selectedVideoPosition);
initWebView(selectedVideo);
wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(myView, params);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
int progress = seekBar.getProgress();
double secs = (progress * totalVideoDuration)/1000;
secs = Math.ceil(secs);
//Log.e("main", "onStopTrackingTouch :: progress = " + progress + "-- secs = " + secs);
mWebView.loadUrl("javascript:m_seekVideo('" + secs + "')");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
//Log.e("mainactivity", "onStartTrackingTouch :: progress = " + seekBar.getProgress());
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
}
});
playButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(videoisPlaying) {
try {
Toast.makeText(getApplicationContext(),"video is paused", Toast.LENGTH_SHORT).show();
videoisPlaying=false;
playButton.setBackgroundResource(R.drawable.play_1);
mWebView.loadUrl("javascript:m_pauseVideo()");
} catch (Exception e) {
e.printStackTrace();
}
}
else
if(!videoisPlaying) {
try {
Toast.makeText(getApplicationContext(),"video is played", Toast.LENGTH_SHORT).show();
videoisPlaying=true;
playButton.setBackgroundResource(R.drawable.pause_1);
mWebView.loadUrl("javascript:m_playVideo()");
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
close.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view)
{
Toast.makeText(AppopenService.this,"close button", Toast.LENGTH_SHORT).show();
mWebView.loadUrl("javascript:m_pauseVideo()");
wm.removeView(myView);
stopSelf();
}
});
backward.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(AppopenService.this,"backward button", Toast.LENGTH_SHORT).show();
previousVideo();
}
});
forward.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(AppopenService.this,"forward button", Toast.LENGTH_SHORT).show();
nextVideo();
}
});
shuffle.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(AppopenService.this,"shuffle button", Toast.LENGTH_SHORT).show();
if (shuffleisOn) {
shuffleisOn = false;
Toast.makeText(getApplicationContext(), "shuffle is off", Toast.LENGTH_SHORT).show();
} else {
genrater_random_number = false;
generateRandomNumber();
if (repeatIsOn) {
repeatIsOn = false;
Toast.makeText(getApplicationContext(), "repeat is off", Toast.LENGTH_SHORT).show();
}
shuffleisOn = true;
Toast.makeText(getApplicationContext(), "shuffle is on", Toast.LENGTH_SHORT).show();
}
}
});
repeat.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(AppopenService.this,"repeat button", Toast.LENGTH_SHORT).show();
if (repeatIsOn) {
repeatIsOn = false;
Toast.makeText(getApplicationContext(), "repeat is off", Toast.LENGTH_SHORT).show();
} else {
if (shuffleisOn) {
shuffleisOn = false;
Toast.makeText(getApplicationContext(), "shuffle is off", Toast.LENGTH_SHORT).show();
}
repeatIsOn = true;
Toast.makeText(getApplicationContext(), "repeat is on", Toast.LENGTH_SHORT).show();
}
}
});
}
void generateRandomNumber() {
if (genrater_random_number == false) {
genrater_random_number = true;
shuffleList.clear();
// Toast.makeText(getApplicationContext(), ""+ videos_play_next_list.size(), Toast.LENGTH_SHORT).show();
for (int i = 0; i < videoList.size(); i++)
{
shuffleList.add(i);
//Toast.makeText(getApplicationContext(), ""+i+"times "+shuffleList.add(i) , Toast.LENGTH_LONG).show();
}
Toast.makeText(getApplicationContext(), "" + shuffleList, Toast.LENGTH_LONG).show();
if (shuffleList.contains(selectedVideoPosition)) {
int index = shuffleList.indexOf(selectedVideoPosition);
//Toast.makeText(this, "index of zero is "+index, Toast.LENGTH_SHORT).show();
//listremove.add(shuffleList.get(index));
shuffleList.remove(index);
}
// Toast.makeText(getApplicationContext(), ""+list , Toast.LENGTH_LONG).show();
Collections.shuffle(shuffleList);
shuffleList.add(0, selectedVideoPosition);
Toast.makeText(getApplicationContext(), "" + shuffleList, Toast.LENGTH_LONG).show();
}
}
private void nextVideo() {
if (repeatIsOn) {
if (selectedVideo == videoList.get(4)) {
selectedVideoPosition = 0;
} else {
selectedVideoPosition++;
}
selectedVideo = videoList.get(selectedVideoPosition);
playvideo(selectedVideo);
} else if (shuffleisOn) {
//generateRandomNumber();
if (selectedVideoPositionForSuffle < videoList.size() - 1) {
selectedVideoPositionForSuffle++;
selectedVideoPosition = shuffleList.get(selectedVideoPositionForSuffle);
selectedVideo = videoList.get(selectedVideoPosition);
playvideo(selectedVideo);
} else {
Toast.makeText(getApplicationContext(), "List of video finished", Toast.LENGTH_SHORT).show();
}
} else {
if (selectedVideo == videoList.get(4)) {
Toast.makeText(getApplicationContext(), "last Video", Toast.LENGTH_SHORT).show();
} else {
selectedVideoPosition++;
selectedVideo = videoList.get(selectedVideoPosition);
playvideo(selectedVideo);
}
}
}
private void previousVideo() {
if (repeatIsOn) {
if (selectedVideo == videoList.get(0)) {
selectedVideoPosition = videoList.size() - 1;
} else {
selectedVideoPosition--;
}
selectedVideo = videoList.get(selectedVideoPosition);
playvideo(selectedVideo);
} else if (shuffleisOn) {
//generateRandomNumber();
if (selectedVideoPositionForSuffle > 0) {
selectedVideoPositionForSuffle--;
selectedVideoPosition = shuffleList.get(selectedVideoPositionForSuffle);
selectedVideo = videoList.get(selectedVideoPosition);
playvideo(selectedVideo);
} else {
Toast.makeText(getApplicationContext(), "starting of video list", Toast.LENGTH_SHORT).show();
}
} else {
if (selectedVideo == videoList.get(0)) {
Toast.makeText(getApplicationContext(), "first Video", Toast.LENGTH_SHORT).show();
} else {
selectedVideoPosition--;
selectedVideo = videoList.get(selectedVideoPosition);
playvideo(selectedVideo);
}
}
}
@SuppressWarnings("deprecation")
@SuppressLint({"NewApi", "JavascriptInterface"})
private void initWebView(String string) {
Log.e("here we are","initWebView Method");
mWebView = (WebView) myView.findViewById(R.id.webView);
mWebView.setClickable(false);
mWebView.setFocusable(false);
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccess(true);
settings.setPluginState(WebSettings.PluginState.ON);
settings.setDomStorageEnabled(true);
settings.setJavaScriptEnabled(true);
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
settings.setSupportZoom(false);
settings.setBuiltInZoomControls(false);
settings.setDisplayZoomControls(false);
//settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
settings.setMediaPlaybackRequiresUserGesture(false);
mWebView.setWebViewClient(new MyWebviewClient());
mWebView.setLayerType(2, null);
mWebView.addJavascriptInterface(new MyJavaScriptInterface(AppopenService.this), "JSHandler");
mWebView.setWebChromeClient(new MyChromwClient());
playvideo(string);
}
private class MyWebviewClient extends WebViewClient {
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// TODO Auto-generated method stub
super.onReceivedError(view, errorCode, description, failingUrl);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
Log.e("main", "shouldOverrideUrlLoading : url = " + url);
if (url.contains("onStateChange")) {
String arr[] = {};
arr = url.split("=");
//int x=Integer.parr[0].toString();
if (arr[1].matches("[0-9]+") && arr[1].length() >= 1) {
PlayerStates = Integer.parseInt(arr[1]);
//Log.d("main", "shouldOverrideUrlLoading : url = " + arr[1]);
}
//Toast.makeText(getApplicationContext(),""+PlayerStates,Toast.LENGTH_SHORT).show();
Log.e("shouldOverrideUrlLoadin", "getting player state is " + PlayerStates);
if (PlayerStates == 0) {
Log.e("shouldOverrideUrlLoadin", "PlayerStates=0");
modifySlider("ENDED");
nextVideo();
}
if (PlayerStates == 3) {
Log.e("shouldOverrideUrlLoadin", "PlayerStates=3");
seekBar.setEnabled(false);
}
else {
Log.e("shouldOverrideUrlLoadin", "PlayerStates=2");
seekBar.setEnabled(true);
}
}
if (url.contains("onPlayTime")) {
if (PlayerStates == 1) {
Log.e("shouldOverrideUrlLoadin", "PlayerStates=1");
String arr[] = {};
arr = url.split("=");
// Log.d("main", "shouldOverrideUrlLoading : url = " + arr[1]);
try {
changeSlider(Float.parseFloat(arr[1]));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
return true;
}
}
private class MyChromwClient extends WebChromeClient {
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
// TODO Auto-generated method stub
// Log.e("main", "consoleMessage : " + consoleMessage.message());
try {
if (consoleMessage.message().matches("[0-9]+") && consoleMessage.message().length() >= 1)
{
totalVideoDuration = Float.parseFloat(consoleMessage.message());
Log.e("charcter at value==", "sdn" + totalVideoDuration);
}
} catch (Exception e) {
}
return super.onConsoleMessage(consoleMessage);
}
}
private class MyJavaScriptInterface {
public AppopenService activity;
public MyJavaScriptInterface(AppopenService activity) {
this.activity = activity;
}
public void setVideoDuration(String duration) {
try {
Log.e("main", "setVideoDuration = " + duration);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
try {
changeSlider(Float.parseFloat(duration));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void setTotalVideoDuration(String duration) {
Log.e("main", "setTotalVideoDuration = " + duration);
try {
totalVideoDuration = Float.parseFloat(duration);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
//}
public void videoEnd() {
modifySlider("ENDED");
}
}
public void playvideo(String videostring)
{
String html = "";
html += "<html>"+"<head>"+"<body>"+"<style>"+"body { margin: 0; width:100%%; height:100%%; }"+
"html { width:100%%; height:100%%; }"+
".embed-container iframe,"+
".embed-container object,"+
".embed-container embed {"+
"position: absolute;"+
"top: 0;"+
"left: 0;"+
"width: 100%% !important;"+
"height: 100%% !important;"+
"}"+
"</style>"+
"</head>"+"<body>"+"<div class=embed-container>"+"<div id=ytplayer></div>"+"</div>"+"<script type='text/javascript' src='https://www.youtube.com/iframe_api'></script>"+"<script type='text/javascript'>"+
"var vID;"+
"function onYouTubeIframeAPIReady()"+
"{"+
"ytplayer=new YT.Player('playerId',{"+
"events:{"+
"'onReady': onPlayerReady,"+
"'onStateChange': onPlayerStateChange,"+
"'onPlaybackQualityChange': onPlayerQualityChange,"+
"'onError': onPlayerError"+
"}"+
"});"+
"}"+"function onPlayerReady(event)"+"{"+
"event.target.playVideo();"+
"setTotalVideoDuration();"+
"}"+
"function onPlayerStateChange(event)"+"{"+
"window.location.href ='ytplayer://onStateChange?data=' + event.data;"+
"}"+
"function onPlayerQualityChange(event)"+"{"+
"window.location.href ='ytplayer://onStateChange?data=' + event.data;"+
"}"+
"function onPlayerError(event)"+
"{"+
"window.location.href = 'ytplayer://onError?data=' + event.data;"+
"}"+
"function m_stopVideo()"+"{"+
"ytplayer.stopVideo();"+
"}"+
"function m_playVideo() {"+
"ytplayer.playVideo();"+
"}"+
"function m_pauseVideo()"+ "{"+
"ytplayer.pauseVideo();"+
"}"+
"function m_seekVideo(time){"+
"ytplayer.seekTo(time, true);"+
"}"+
"function setTotalVideoDuration(){"+
//return player.getDuration();
"console.log(ytplayer.getDuration());"+
/*"JSHandler.setTotalVideoDuration(ytplayer.getDuration());"+*/
"}"+
"function onPlayTime(time){"+
/*"JSHandler.setVideoDuration(time);"+*/
"}"+
"function getCurrentTime() {"+
"var state = ytplayer.getPlayerState();"+
"if (state == YT.PlayerState.PLAYING) {"+
"time = ytplayer.getCurrentTime();"+
"window.location.href = 'ytplayer://onPlayTime?data=' + time;"+
"onPlayTime(time);"+
"}"+
"}"+
"window.setInterval(getCurrentTime, 1000);"+
"function m_loadVideo(vidID)"+"{"+
"vID=vidID;"+
"ytplayer.loadVideoById(vID, 0, '"+"large"+"');"+
"setTotalVideoDuration();"+
"}"+
"</script>";
/// set video id here
html +=" <iframe id='playerId' type='text/html' width='100%%' height='100%%' src='https://www.youtube.com/embed/"+videostring+"?enablejsapi=1&playsinline=1&autoplay=1&controls=0&fs=0&rel=0&showinfo=0&vq=medium&iv_load_policy=3&modestbranding=1' frameborder=0></iframe>";
html += "</body></html>";
// mWebView.loadData(html, "text/html", null);
mWebView.loadDataWithBaseURL("http://www.youtube.com/", html, "text/html", "utf-8", "");
}
private void changeSlider(float time) {
float progress = (time/totalVideoDuration) * 1000;
final double d = Math.ceil(progress);
// TODO Auto-generated method stub
seekBar.setProgress((int) d);
}
private void modifySlider(final String flag)
{
if (flag.equals("ENDED"))
seekBar.setProgress(MAX);
}
/////////////////////previous code//////////////////////////////////////////////////////
@Override
public void onLowMemory() {
// TODO Auto-generated method stub
super.onLowMemory();
// Toast.makeText(getBaseContext()," low memory call", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
// TODO Auto-generated method stub
super.onTaskRemoved(rootIntent);
//Toast.makeText(getBaseContext()," task remov yes", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.e("here we are","onStartCommand");
return START_NOT_STICKY;
}
}
я взял различные разрешения
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
я ни мог найти проблему, ни решение , Пожалуйста, помогите мне. Заранее спасибо.
Это происходит со мной даже во Фрагменте или Деятельности. Но это происходит только на некоторых API. Например, API 23 работает отлично. –