Playing youtube videos smoothly in web view - android

I am building an app where a user can see a YouTube video and can see the images for which link is coming from the sever. To play YouTube video embed key's value is coming from server as
`<div id="_cvp_11204"><span>
</span></div>
<script type="text/javascript">
(function(){var a;a=new XMLHttpRequest;a.onreadystatechange=function(){rs=a.readyState;if(4==rs&&200==a.status){var c=JSON.parse(a.responseText),b;for(b in c.payload)if(c.payload.hasOwnProperty(b)){var d=c.payload[b];document.getElementById("cvp"+b).innerHTML=d.view}}};a.open("GET","http://dummyurl.com/media.ids=?11134 ));a.send()})(window);
</script>`
and i am able to play the video also but i am facing few issue in terms of performance.
1) sometimes voices starts but video starts showing after some time.
2) Sometime controls doesn't show up.
3) How can i play the video directly in fullscreen mode?Currently to play the video in full screen mode i have to click on the max control to play it.
As is the activity class for webview
public class MainActivity extends Activity {
protected FrameLayout webViewPlaceholder;
protected WebView webView;
private FrameLayout mContentView;
private MyWebChromeClient mWebChromeClient = null;
private View mCustomView;
private FrameLayout mCustomViewContainer;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("Oncreate is getting called ---------------------------");
// Initialize the UI
if(savedInstanceState == null){
initUI();
}
}
protected void initUI()
{
// Retrieve UI elements
webViewPlaceholder = ((FrameLayout)findViewById(R.id.webViewPlaceholder));
mContentView = webViewPlaceholder;
// Initialize the WebView if necessary
if (webView == null)
{
System.out.println("webView == null -----------------------------------");
// Create the webview
webView = new WebView(this);
webView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setAllowContentAccess(true);
webSettings.setDomStorageEnabled(true);
webSettings.setRenderPriority(RenderPriority.HIGH);
webSettings.setUseWideViewPort(false);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
//--------------------------------------------------------
if (Build.VERSION.SDK_INT < 8) {
webSettings.setPluginsEnabled(true);
} else {
webSettings.setPluginState(PluginState.ON);
}
mWebChromeClient = new MyWebChromeClient();
webView.setWebChromeClient(mWebChromeClient);
// Load the URLs inside the WebView, not in the external web browser
//webView.setWebViewClient(new WebViewClient());
// Load a page
loadWebView("asfas");
}
// Attach the WebView to its placeholder
webViewPlaceholder.addView(webView);
}
private void loadWebView(final String url) {
String s = ReadFromfile("link.txt", MainActivity.this);
s = "<html><body>"+s+"</body></html>";
webView.loadDataWithBaseURL("",Html.fromHtml(s).toString(),"text/html", "UTF-8",null);
}
public String ReadFromfile(String fileName, Context context) {
StringBuilder ReturnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets()
.open(fileName, context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
ReturnString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return ReturnString.toString();
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
if (webView != null)
{
// Remove the WebView from the old placeholder
System.out.println("web view is removed from the holder -------------------------");
webViewPlaceholder.removeView(webView);
}
super.onConfigurationChanged(newConfig);
// Load the layout resource for the new configuration
setContentView(R.layout.activity_main);
// Reinitialize the UI
initUI();
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
System.out.println("onSaveInstanceState -------------------------");
// Save the state of the WebView
webView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
System.out.println("onRestoreInstanceState -------------------------");
// Restore the state of the WebView
webView.restoreState(savedInstanceState);
}
private class MyWebChromeClient extends WebChromeClient {
FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT);
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mContentView.setVisibility(View.GONE);
mCustomViewContainer = new FrameLayout(MainActivity.this);
mCustomViewContainer.setLayoutParams(LayoutParameters);
mCustomViewContainer.setBackgroundResource(android.R.color.black);
view.setLayoutParams(LayoutParameters);
// Sometimes getting remove view first it parent excepetion on moto devices
//webViewPlaceholder.removeView(webView);
mCustomViewContainer.addView(view);
mCustomView = view;
mCustomViewCallback = callback;
mCustomViewContainer.setVisibility(View.VISIBLE);
setContentView(mCustomViewContainer);
}
#Override
public void onHideCustomView() {
if (mCustomView == null) {
return;
} else {
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
setContentView(mContentView);
}
}
}
}
And in Manifest also I have set the hardwareaccelarated = true.
here is the video when it starts with controls
and here when i click on maximize button video gets full screen which i want without clicking on max button but video should directly play in fullscreen mode.
So mainly, how I can speed up and increase the performance of my WebView?

Related

How to clear Webview content to change the video in Android Oreo

In My activity I have a Webview at the top which plays the video inside it.
below the Webview I have a list of videos to select. For Android versions before Oreo when I select the new video it always plays in the Webview. But in Oreo it doesn't work, It always plays the first video Which i Selected. I have read the document of Oreo it says that
Calling clearFormData() no longer has any effect.
I am looking for some alternative but couldn't find any solution. Below is the my work which I have done so for
private void initViews() {
toolbar = findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getString(R.string.app_name));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
recyclerView = findViewById(R.id.recycler_view);
progressBar = findViewById(R.id.progressBar3);
initWebView();
if (recyclerView != null) {
initRecyclerView(model);
}
AdView adView= findViewById(R.id.ad_view);
admobUtils.loadBannerAd(adView);
}
public void initWebView() {
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setSaveFormData(false);
webView.clearFormData();
webView.clearCache(true);
webView.clearHistory();
webView.setWebViewClient(new WebViewClient() {
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
view.clearHistory();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
RXEventBusUtils.getInstance().postEvent(new MediaPlayerEvent());
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
webView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
}
});
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setDisplayZoomControls(false);
String htmlData;
if (Constants.isFullScreen) {
htmlData = getHtmlDataLanscape(model.getVideo_url());
} else {
htmlData = getHtmlData(model.getVideo_url());
}
webView.loadData(htmlData, "text/html", null);
}
This is where I am selecting the video from list.
public void selectVideo(){
progressBar.setVisibility(View.VISIBLE);
model = new MyModel();
model = ((SelectVideoEvent) event).getModel();
if (model.getVideo_url() != null && !model.getVideo_url().isEmpty()) {
initRecyclerView(model);
initWebView();
Bundle bundleFire = new Bundle();
Application.getFireBaseInstance().logEvent("video_from_list",bundleFire);
}
}
Please can anybody tell me how to change the webview content in Android Oreo
As clearFormData() no longer has any effect in android version Oreo. The best way is to create a Webview as a new view. For that purpose you should use a frameLayout inside xml file, and inside java file, create webview dynamically and add that webview in framelayout as a view.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp">
<FrameLayout
android:id="#+id/myWeb"
android:layout_width="match_parent"
android:layout_height="200dp"
android:alwaysDrawnWithCache="true" />
</RelativeLayout>
public class TestActivity extends AppCompatActivity {
FrameLayout frameLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
frameLayout = findViewById(R.id.myWeb);
setWebView();
/*setWebViewToLoadData*/
}
public void setWebView(){
frameLayout.removeAllViews();
WebView webView = new WebView(this);
webView.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
frameLayout.addView(webView);
}
}
And indside your selectVideo method call again setWebView

Capture Full Webview to Bitmap

I want to ask about webview :
I can't capture full page in webview. I can only capture the view that appears on the screen only, as I want to capture the full page. How to?
This is my webview :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
WebView.enableSlowWholeDocumentDraw();
}
setContentView(R.layout.main_activity);
final WebView webview = (WebView) findViewById(R.id.WebViewLayout);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(webview, url);
}
});
webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webview.setDrawingCacheEnabled(true);
webview.loadUrl("https://example.com");
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available",
Toast.LENGTH_LONG).show();
finish();
}
}
and this is to convert into bitmap
private void Print_BMP(){
Bitmap mBitmap = Bitmap.createBitmap(imageViewPicture.getDrawingCache());
int nMode = 0;
int nPaperWidth = 384;
if(width_58mm.isChecked())
nPaperWidth = 384;
if(mBitmap != null)
{
byte[] data = PrintPicture.POS_PrintBMP(mBitmap, nPaperWidth, nMode);
SendDataByte(Command.ESC_Init);
SendDataByte(Command.LF);
SendDataByte(data);
SendDataByte(PrinterCommand.POS_Set_PrtAndFeedPaper(30));
SendDataByte(PrinterCommand.POS_Set_Cut(1));
SendDataByte(PrinterCommand.POS_Set_PrtInit());
}
}
and this is for keylistener
private void KeyListenerInit() {
btnScanButton = (Button)findViewById(R.id.button_scan);
btnScanButton.setOnClickListener(this);
width_58mm = (RadioButton)findViewById(R.id.width_58mm);
width_58mm.setOnClickListener(this);
imageViewPicture = (WebView) findViewById(R.id.WebViewLayout);
imageViewPicture.setOnClickListener(this);
}
Capture, scroll, capture, repeat as necessary.
Then assemble the individual images if you need to after that.
The add-in browser tools that provide this functionality appear to work in this same way.

WebChromeClient not working Android

I got a progress bar, a Full screen video playback method (for playing youtube videos in full-screen), and public boolean shouldOverrideUrlLoading for handling URL's within the WebView but i cannot get all of the three to work together, i tried the following three approaches and it seems like i need duplicate webviewClient and webChromeclients to make everything work which depend on them
Approach 1 - Progress Bar is not working (stuck on 0%)
public class MainActivity extends Activity {
private WebView mWebView;
private EditText urlEditText;
private ProgressBar progress;
// FULL-SCREEN VIDEO-1
private LinearLayout mContentView;
private FrameLayout mCustomViewContainer;
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
private WebChromeClient mWebChromeClient;
// FULL-SCREEN VIDEO-1
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// FULL-SCREEN VIDEO-2
mContentView = (LinearLayout) findViewById(R.id.linearlayout);
mWebView = (WebView) findViewById(R.id.webView);
mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);
mWebChromeClient = new WebChromeClient() {
#Override
public void onShowCustomView(View view,
WebChromeClient.CustomViewCallback callback) {
// if a view already exists then immediately terminate the new
// one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// hide main browser view
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
#Override
public void onHideCustomView() {
if (mCustomView == null)
return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
}
};
// FULL-SCREEN VIDEO-2
WebSettings webSettings = mWebView.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new HelloWebViewClient());
// Download manager
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
// **//
// URL BAR AND PROGRESS BAR
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
urlEditText = (EditText) findViewById(R.id.urlField);
// Use Done/search button in keyboard as go button
urlEditText.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
// Toast.makeText(getApplicationContext(), "some key pressed",
// Toast.LENGTH_LONG).show();
String url = urlEditText.getText().toString();
if (url.endsWith(".ac") || url.endsWith(".ac.uk")
|| url.endsWith(".ad") || url.endsWith(".zw")) {
if (!url.startsWith("http://")
&& !url.startsWith("https://")) {
url = "http://" + url;
}
} else
url = "https://www.google.com/search?q="
+ url.replace(" ", "+");// Prefix (replace spaces
// with a '+' sign)
mWebView.loadUrl(url);
if (validateUrl(url)) {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
MainActivity.this.progress.setProgress(10);
}
return false;
}
private boolean validateUrl(String url) {
return true;
}
});
// **//
}
private class MyWebViewClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
MainActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url) {
webview.setWebChromeClient(mWebChromeClient);
webview.loadUrl(url);
return true;
}
}
// FULL-SCREEN VIDEO-3
#Override
protected void onStop() {// plays video outside frame on back button and
// prevents from going back
super.onStop();
if (mCustomView != null) {
if (mCustomViewCallback != null)
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
#Override
public void onBackPressed() {// hide custom view (in which the video plays)
// on back button
super.onBackPressed();
if (mCustomView != null) {
mWebChromeClient.onHideCustomView();
} else {
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {// prevents the
// custom view from
// running in
// background when
// app is closed
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
// FULL-SCREEN VIDEO-3
}
}
Approach 2 - Full Screen Not working
public class MainActivity extends Activity {
private WebView mWebView;
private EditText urlEditText;
private ProgressBar progress;
// FULL-SCREEN VIDEO-1
private LinearLayout mContentView;
private FrameLayout mCustomViewContainer;
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
private WebChromeClient mWebChromeClient;
// FULL-SCREEN VIDEO-1
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// FULL-SCREEN VIDEO-2
mContentView = (LinearLayout) findViewById(R.id.linearlayout);
mWebView = (WebView) findViewById(R.id.webView);
mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);
mWebChromeClient = new WebChromeClient() {
#Override
public void onShowCustomView(View view,
WebChromeClient.CustomViewCallback callback) {
// if a view already exists then immediately terminate the new
// one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// hide main browser view
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
#Override
public void onHideCustomView() {
if (mCustomView == null)
return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
}
};
// FULL-SCREEN VIDEO-2
WebSettings webSettings = mWebView.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new HelloWebViewClient());
mWebView.setWebChromeClient(new mWebChromeClient());
// Download manager
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
// **//
// URL BAR AND PROGRESS BAR
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
urlEditText = (EditText) findViewById(R.id.urlField);
// Use Done/search button in keyboard as go button
urlEditText.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
// Toast.makeText(getApplicationContext(), "some key pressed",
// Toast.LENGTH_LONG).show();
String url = urlEditText.getText().toString();
if (url.endsWith(".ac") || url.endsWith(".ac.uk")
|| url.endsWith(".ad") || url.endsWith(".zw")) {
if (!url.startsWith("http://")
&& !url.startsWith("https://")) {
url = "http://" + url;
}
} else
url = "https://www.google.com/search?q="
+ url.replace(" ", "+");// Prefix (replace spaces
// with a '+' sign)
mWebView.loadUrl(url);
if (validateUrl(url)) {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
MainActivity.this.progress.setProgress(10);
}
return false;
}
private boolean validateUrl(String url) {
return true;
}
});
// **//
}
private class mWebChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
MainActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url) {
webview.loadUrl(url);
return true;
}
}
// FULL-SCREEN VIDEO-3
#Override
protected void onStop() {// plays video outside frame on back button and
// prevents from going back
super.onStop();
if (mCustomView != null) {
if (mCustomViewCallback != null)
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
#Override
public void onBackPressed() {// hide custom view (in which the video plays)
// on back button
super.onBackPressed();
if (mCustomView != null) {
mWebChromeClient.onHideCustomView();
} else {
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {// prevents the
// custom view from
// running in
// background when
// app is closed
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
// FULL-SCREEN VIDEO-3
}
}
Approach 3 - shouldOverrideUrlLoading not working
public class MainActivity extends Activity {
private WebView mWebView;
private EditText urlEditText;
private ProgressBar progress;
// FULL-SCREEN VIDEO-1
private LinearLayout mContentView;
private FrameLayout mCustomViewContainer;
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
private WebChromeClient mWebChromeClient;
// FULL-SCREEN VIDEO-1
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// FULL-SCREEN VIDEO-2
mContentView = (LinearLayout) findViewById(R.id.linearlayout);
mWebView = (WebView) findViewById(R.id.webView);
mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);
mWebChromeClient = new WebChromeClient() {
#Override
public void onShowCustomView(View view,
WebChromeClient.CustomViewCallback callback) {
// if a view already exists then immediately terminate the new
// one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// hide main browser view
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
#Override
public void onHideCustomView() {
if (mCustomView == null)
return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
}
};
// FULL-SCREEN VIDEO-2
WebSettings webSettings = mWebView.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebChromeClient(new HelloWebViewClient());
// Download manager
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
// **//
// URL BAR AND PROGRESS BAR
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
urlEditText = (EditText) findViewById(R.id.urlField);
// Use Done/search button in keyboard as go button
urlEditText.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
// Toast.makeText(getApplicationContext(), "some key pressed",
// Toast.LENGTH_LONG).show();
String url = urlEditText.getText().toString();
if (url.endsWith(".ac") || url.endsWith(".ac.uk")
|| url.endsWith(".ad") || url.endsWith(".zw")) {
if (!url.startsWith("http://")
&& !url.startsWith("https://")) {
url = "http://" + url;
}
} else
url = "https://www.google.com/search?q="
+ url.replace(" ", "+");// Prefix (replace spaces
// with a '+' sign)
mWebView.loadUrl(url);
if (validateUrl(url)) {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
MainActivity.this.progress.setProgress(10);
}
return false;
}
private boolean validateUrl(String url) {
return true;
}
});
// **//
}
private class HelloWebViewClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
MainActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
private class HelloWebViewClient1 extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url) {
webview.setWebChromeClient(mWebChromeClient);
webview.loadUrl(url);
return true;
}
}
// FULL-SCREEN VIDEO-3
#Override
protected void onStop() {// plays video outside frame on back button and
// prevents from going back
super.onStop();
if (mCustomView != null) {
if (mCustomViewCallback != null)
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
#Override
public void onBackPressed() {// hide custom view (in which the video plays)
// on back button
super.onBackPressed();
if (mCustomView != null) {
mWebChromeClient.onHideCustomView();
} else {
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {// prevents the
// custom view from
// running in
// background when
// app is closed
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
// FULL-SCREEN VIDEO-3
}
}

button to display url not working anymore

i was working on a webView had it working but the flash videos didn't work.
After a little bit of searching i found a webview code that displays videos.
webview video
this is my old code
private static final String LOG_TAG = "Web";
private WebView mWebView;
public static final String URL = "";
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.web);
mWebView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = mWebView.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
String turl = getIntent().getStringExtra(URL);
mWebView.loadUrl(turl);
;
}
#Override
public void onBackPressed() {
finish();
}
/**
* Provides a hook for calling "alert" from javascript. Useful for debugging
* your javascript.
*/
final class MyWebChromeClient extends WebChromeClient {
#Override
public boolean onJsAlert(WebView view, String url, String message,
JsResult result) {
Log.d(LOG_TAG, message);
result.confirm();
return true;
}
}
so i replaced it with the mainactivity from the source and added
String turl = getIntent().getStringExtra(URL);
and
public static final String URL = "";
and made some changes so it loads the class names i use
so now i've got this
private WebView webView;
public static final String URL = "";
private FrameLayout customViewContainer;
private WebChromeClient.CustomViewCallback customViewCallback;
private View mCustomView;
private myWebChromeClient mWebChromeClient;
private myWebViewClient mWebViewClient;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
webView = (WebView) findViewById(R.id.webView);
mWebViewClient = new myWebViewClient();
webView.setWebViewClient(mWebViewClient);
mWebChromeClient = new myWebChromeClient();
webView.setWebChromeClient(mWebChromeClient);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSaveFormData(true);
String turl = getIntent().getStringExtra(URL);
webView.loadUrl(turl);
}
public boolean inCustomView() {
return (mCustomView != null);
}
public void hideCustomView() {
mWebChromeClient.onHideCustomView();
}
#Override
protected void onPause() {
super.onPause(); //To change body of overridden methods use File | Settings | File Templates.
webView.onPause();
}
#Override
protected void onResume() {
super.onResume(); //To change body of overridden methods use File | Settings | File Templates.
webView.onResume();
}
#Override
protected void onStop() {
super.onStop(); //To change body of overridden methods use File | Settings | File Templates.
if (inCustomView()) {
hideCustomView();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (inCustomView()) {
hideCustomView();
return true;
}
if ((mCustomView == null) && webView.canGoBack()) {
webView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
class myWebChromeClient extends WebChromeClient {
private Bitmap mDefaultVideoPoster;
private View mVideoProgressView;
#Override
public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
onShowCustomView(view, callback); //To change body of overridden methods use File | Settings | File Templates.
}
#Override
public void onShowCustomView(View view,CustomViewCallback callback) {
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mCustomView = view;
webView.setVisibility(View.GONE);
customViewContainer.setVisibility(View.VISIBLE);
customViewContainer.addView(view);
customViewCallback = callback;
}
#Override
public View getVideoLoadingProgressView() {
if (mVideoProgressView == null) {
LayoutInflater inflater = LayoutInflater.from(Web.this);
mVideoProgressView = inflater.inflate(R.layout.video_progress, null);
}
return mVideoProgressView;
}
#Override
public void onHideCustomView() {
super.onHideCustomView(); //To change body of overridden methods use File | Settings | File Templates.
if (mCustomView == null)
return;
webView.setVisibility(View.VISIBLE);
customViewContainer.setVisibility(View.GONE);
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
customViewContainer.removeView(mCustomView);
customViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
class myWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url); //To change body of overridden methods use File | Settings | File Templates.
}
}
i use this code for my button to open the url in webview
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Intent k = new Intent(this, Web.class);
k.putExtra(com.papers.test.Web.URL,
"http://www.telegraaf.mobi");
startActivity(k);
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.onlinekranten);
View secondButton = findViewById(R.id.button1);
secondButton.setOnClickListener(this);
}
in my old web.class this worked just fine but now when i press the button i'm getting a fc, can anyone help me out with this problem?
logcat
06-07 12:38:55.310: E/AndroidRuntime(3236): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.papers.test/com.papers.test.Web}: java.lang.NullPointerException
Its looks like your button needs to be declared
I like to do it above onCreate to use it any where
Button secondButton;

Android ICS Flash WebView full screen throws NullPointerException

My application uses a WebView to display flash video contents. Everything seems to go smoothly
until you try to play full screen on Android ICS devices. It works fine on devices with lower version.
On ICS devices it throws a NullPointerException.
Here is my code:
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setVerticalScrollbarOverlay(true);
webView.setWebViewClient(new WebViewClient() {
private ProgressDialog pd;
#Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
pd = new ProgressDialog(TrainingDetailActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setMessage("Loading");
pd.show();
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
this.dismissDialog();
super.onPageFinished(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view,
String url) {
return false;
}
private void dismissDialog() {
if (pd != null) {
pd.dismiss();
pd = null;
}
}
});
webView.loadDataWithBaseURL(baseUrl, htmlstr, "text/html", "utf-8", null);
After some digging, I found out that in ICS the android.webkit.PluginFullScreenHolder show() method gets called and throws
an NullExceptionPointer. The problem lays there, not on my code.
I tried some work around but none of them works.
- Work around : I added this line:
webView.setWebChromeClient(new WebChromeClient() );
With this work around the NullPointerException does not occur, but the video plays with no sound, and won't switch to
Full screen mode.
I looked around stackoverflow for solutions, the closest which seems to solve my problem is this answer:
https://stackoverflow.com/a/9921073/1503155
But unfortunately the answerer didn't explain what is the variable base in his code snippet and I am still stuck.
My question is, is there a way to work around this bug. Is yes, How?
Thanks in advance.
My boss gave me permission to share this with you.
I had the same issue for a long time before cobbling this together.
Create this as a class, and set the chrome client of your WebView:
WebView.setWebChromeClient(...);
To this:
public class FullscreenableChromeClient extends WebChromeClient {
protected Activity mActivity = null;
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
private int mOriginalOrientation;
private FrameLayout mContentView;
private FrameLayout mFullscreenContainer;
private static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
public FullscreenableChromeClient(Activity activity) {
this.mActivity = activity;
}
#Override
public void onShowCustomView(View view, int requestedOrientation, WebChromeClient.CustomViewCallback callback) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mOriginalOrientation = mActivity.getRequestedOrientation();
FrameLayout decor = (FrameLayout) mActivity.getWindow().getDecorView();
mFullscreenContainer = new FullscreenHolder(mActivity);
mFullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
decor.addView(mFullscreenContainer, COVER_SCREEN_PARAMS);
mCustomView = view;
setFullscreen(true);
mCustomViewCallback = callback;
mActivity.setRequestedOrientation(requestedOrientation);
}
super.onShowCustomView(view, requestedOrientation, callback);
}
#Override
public void onHideCustomView() {
if (mCustomView == null) {
return;
}
setFullscreen(false);
FrameLayout decor = (FrameLayout) mActivity.getWindow().getDecorView();
decor.removeView(mFullscreenContainer);
mFullscreenContainer = null;
mCustomView = null;
mCustomViewCallback.onCustomViewHidden();
mActivity.setRequestedOrientation(mOriginalOrientation);
}
private void setFullscreen(boolean enabled) {
Window win = mActivity.getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_FULLSCREEN;
if (enabled) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
if (mCustomView != null) {
mCustomView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
} else {
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
}
win.setAttributes(winParams);
}
private static class FullscreenHolder extends FrameLayout {
public FullscreenHolder(Context ctx) {
super(ctx);
setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
}
#Override
public boolean onTouchEvent(MotionEvent evt) {
return true;
}
}
}
Thanks for upstairs' code
Host's problem I was encountered。
In Activity I resoled like that。
#Override
public void onBackPressed() {
Log.e(TAG, "onBackPressed");
if(mCustomView!=null){
mFull.onHideCustomView();
}else{
super.onBackPressed();
}
}

Categories

Resources