Android ICS Flash WebView full screen throws NullPointerException - android

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

Related

Android How to make full screen Video?

When I make a video full screen in WebView, the toolbar is not hidden. How can I hide it? Below you can see the codes I use.I'm using fragment and the navigation drawer menu.
When I make a video full screen in WebView, the toolbar is not hidden. How can I hide it? Below you can see the codes I use.I'm using fragment and the navigation drawer menu.
Full screen
public class searchWebFragment extends Fragment {
public searchWebFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.searchwb, container, false);
final ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.progressBarHome);
final WebView webView = (WebView) v.findViewById(R.id.wv_home);
final EditText araTxt = (EditText)v.findViewById(R.id.araTxt);
final Button araBtn = (Button)v.findViewById(R.id.araBtn);
final TextView uyariTxt = (TextView)v.findViewById(R.id.uyariTxt);
progressBar.setVisibility(View.INVISIBLE);
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView webView, int i, String s, String d1) {
webView.loadUrl("file:///android_asset/error.html");
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.INVISIBLE);
}
});
webView.getSettings().setBuiltInZoomControls(true);
webView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, url);
DownloadManager dm = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getActivity().getApplicationContext(), "Dosya İndiriliyor", //To notify the Client that the file is being downloaded
Toast.LENGTH_LONG).show();
}
});
webView.setVisibility(View.INVISIBLE);
araBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
webView.setVisibility(View.VISIBLE);
String aranacaksey = araTxt.getText().toString();
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setAppCacheEnabled(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
String url = "http://www.ifsalar.16mb.com/?s=" + aranacaksey;
webView.loadUrl(url);
araTxt.setVisibility(View.INVISIBLE);
araBtn.setVisibility(View.INVISIBLE);
uyariTxt.setVisibility(View.INVISIBLE);
}
});
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (webView.canGoBack()) {
webView.goBack();
}
return true;
}
return false;
}
});
return v;
}
}
I would recommend you to try out the follow code and remove the listeners which are related to loading the contents of your WebView.
You need to implement the method to load the website in your webview first.
private void loadWebsite() {
ConnectivityManager connectivityManager = (ConnectivityManager) getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager .getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
mWebView.loadUrl("yourURL");
} else {
mWebView.setVisibility(View.GONE);
}
}
From here, you need to implement 2 different class "Browser_Home" and "MyChrome". For testing purposes, just write it outside searchWebFragment and later on you can implement it as a separate java file. With only the Browser_Home class, the fullscreen button will be disabled. When MyChrome class is added, fullscreen button is enabled and toolbar should disappear as intended.
class Browser_home extends WebViewClient {
Browser_home() {
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
setTitle(view.getTitle());
progressBar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
private class MyChrome extends WebChromeClient {
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
protected FrameLayout mFullscreenContainer;
private int mOriginalOrientation;
private int mOriginalSystemUiVisibility;
MyChrome() {}
public Bitmap getDefaultVideoPoster()
{
if (mCustomView == null) {
return null;
}
return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573);
}
public void onHideCustomView()
{
((FrameLayout)getWindow().getDecorView()).removeView(this.mCustomView);
this.mCustomView = null;
getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility);
setRequestedOrientation(this.mOriginalOrientation);
this.mCustomViewCallback.onCustomViewHidden();
this.mCustomViewCallback = null;
}
public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback)
{
if (this.mCustomView != null)
{
onHideCustomView();
return;
}
this.mCustomView = paramView;
this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
this.mOriginalOrientation = getRequestedOrientation();
this.mCustomViewCallback = paramCustomViewCallback;
((FrameLayout)getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1));
getWindow().getDecorView().setSystemUiVisibility(3846);
}
}
And finally, apply the following functions and attributes to your webview and give it another try. Remember to apply these within your OnCreate method:
mWebView.setWebViewClient(new Browser_home());
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
loadWebsite();
Let me know if this works and I can credit the corresponding person for the assistance with the code and classes.
create a folder row and copy the video on raw folder on resources and do the following steps,
On your XML file add VideoView,
<VideoView
android:id="#+id/vdoPlayer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"/>
On your .java class file do,
Uri uri = Uri.parse("android.resource://Your package name Here/" + R.raw.welcome_video);
vdoPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
vdoPlayer.setVideoURI(uri);
vdoPlayer.start();

How to clear Http Basic Auth username and password from cache - android webview

I am using android webview to display a web page that requires basic authentication. I have the code that takes in username and password and allows successful login to the web page. But I want to clear the username and password from cache when the user visits the webview again. Looks like once you enter username and password for basic auth, it keeps that in cache and logs you in automatically.
I have tried
WebViewDatabase webViewDB = WebViewDatabase.getInstance(getActivity());
webViewDB.clearHttpAuthUsernamePassword();
I have also tried webview.clearFormData, webview.clearCache
But it doesn't seem to work. It logged me in automatically without the prompt to enter username and password.
Here is my full code for webview fragment.
public class WebViewFragment extends Fragment {
private static final String LOG_TAG = WebViewFragment.class.getName();
private ProgressBar progressBar;
private View footerV;
private String urlToLoad;
private int footerVisibility;
private int failureCount = 0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.web_fragment, container, false);
try {
init(rootView);
} catch (Exception e) {
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getActivity()));
}
return rootView;
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (footerV != null) footerV.setVisibility(footerVisibility);
}
private void init(View rootView) {
Bundle bundle = getArguments();
ConstraintLayout navBarCL = (ConstraintLayout) rootView.findViewById(R.id.navBar);
progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
if (bundle.getBoolean(BundleConstants.WEB_HIDE_HEADER)) {
navBarCL.setVisibility(View.GONE);
} else {
navBarCL.setVisibility(View.VISIBLE);
ImageView backButtonIV = (ImageView) rootView.findViewById(R.id.backButtonImage);
backButtonIV.setOnClickListener(view -> navigateBack());
String title = bundle.getString(BundleConstants.WEB_HEADER_TEXT);
TextView headerTextTV = (TextView) rootView.findViewById(R.id.headerText);
headerTextTV.setText(title);
}
WebView webView = (WebView) rootView.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setWebViewClient(getClient());
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onCloseWindow(WebView window) {
super.onCloseWindow(window);
navigateBack();
}
});
footerV = getActivity().findViewById(R.id.footer);
footerVisibility = footerV.getVisibility();
if (bundle.getBoolean(BundleConstants.WEB_SHOW_FOOTER)) {
footerV.setVisibility(View.VISIBLE);
} else {
footerV.setVisibility(View.GONE);
}
urlToLoad = bundle.getString(BundleConstants.WEB_URL);
Log.d(LOG_TAG, "Opening url :" + urlToLoad);
webView.loadUrl(urlToLoad);
}
#NonNull
private WebViewClient getClient() {
WebViewDatabase webViewDB = WebViewDatabase.getInstance(getActivity());
webViewDB.clearHttpAuthUsernamePassword();
return new WebViewClient() {
#Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
++failureCount;
showProgressBar();
LoginDialog loginDialog = new LoginDialog(getContext(), getFragment(), handler, failureCount);
loginDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
hideProgressBar();
}
};
}
public void hideProgressBar() {
if (progressBar != null) progressBar.setVisibility(View.GONE);
}
public void showProgressBar() {
if (progressBar != null) progressBar.setVisibility(View.VISIBLE);
}
private WebViewFragment getFragment() {
return this;
}
public String getUrlToLoad() {
return urlToLoad;
}
protected void navigateBack() {
footerV.setVisibility(footerVisibility);
getFragmentManager().popBackStack();
}
}
Please provide some suggestions.
Try this
WebView webView = (WebView) rootView.findViewById(R.id.webView);
webView.clearCache(true);

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

Playing youtube videos smoothly in web view

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?

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;

Categories

Resources