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
}
}
Related
hi guys i want that user can save images(which are displayed inside fragment webview) to there gallery.I want that user will able to save image to there gallery which is displayed in webview. i checked the internet but non of the code work for me. can you give me a complete working code according to my fragment code . im new to android studio and a 10th grade student pls help me
public class BlankFragment extends Fragment {
public Handler h;
ProgressBar progressBar;
public AdView adView;
public WebView mWebView;
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mWebView.restoreState(savedInstanceState);
}
public BlankFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view
= inflater.inflate(R.layout.fragment_blank, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
progressBar.setMax(100);
progressBar.setProgress(1);
mWebView = (WebView) view.findViewById(R.id.hu);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setVerticalScrollBarEnabled(true);
mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.setHorizontalScrollBarEnabled(true);
this.mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.loadUrl("https://stockphoto.com/search.php?q=poo+emoji");
mWebView.setOnKeyListener(new View.OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == MotionEvent.ACTION_UP
&& mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return false;
}
}); mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
});
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
progressBar.setVisibility(View.GONE);
}
});
return view;
}
}
You have to decode HTML:
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
After that get Image Tag from it then you can get mages from it and write to sd card.
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();
I've created Android App with the webview. When trying to sign in with Google, it first asks for username & password, then the screen with the message 'Please close this window' shows up & nothing happens.
Also, the user is not logged in.
P.S. This works absolutely fine with my mobile website which itself is ported to Android Webview App. Can anyone tell why that doesn't work? I'm completely new to Android.
Two things in webview create problems in google sign-in.
Google doesn't allow us to sign-in from webview nowadays. So, User-Agent needs to be customized.
Popup handling in webview isn't appropriate. So, a function override is needed.
Using custom User-Agent and an AlertDialog in WebChromeClient to handle popups solve the issues for me.
Here's the full code:
public class MainActivity extends AppCompatActivity {
private Context contextPop;
private WebView webViewPop;
private AlertDialog builder;
private String url = "https://example.com";
private WebView webView;
private String userAgent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// to continue loading a given URL in the current WebView.
// needed to handle redirects.
return false;
}
});
webView.loadUrl(url);
WebSettings webSettings = webView.getSettings();
// Set User Agent
//userAgent = System.getProperty("http.agent");
// the upper line sometimes causes "403: disallowed user agent error"
userAgent = "";
webSettings.setUserAgentString(userAgent + "Your App Info/Version");
// Enable Cookies
CookieManager.getInstance().setAcceptCookie(true);
if(android.os.Build.VERSION.SDK_INT >= 21)
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
// WebView Tweaks
webSettings.setJavaScriptEnabled(true);
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
webSettings.setAppCacheEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
// Handle Popups
webView.setWebChromeClient(new CustomChromeClient());
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
contextPop = this.getApplicationContext();
}
#Override
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
}
else {
//super.onBackPressed();
// Terminate the app
finishAffinity();
System.exit(0);
}
}
class CustomChromeClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
webViewPop = new WebView(contextPop);
webViewPop.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// to continue loading a given URL in the current WebView.
// needed to handle redirects.
return false;
}
});
// Enable Cookies
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
if(android.os.Build.VERSION.SDK_INT >= 21) {
cookieManager.setAcceptThirdPartyCookies(webViewPop, true);
cookieManager.setAcceptThirdPartyCookies(webView, true);
}
WebSettings popSettings = webViewPop.getSettings();
// WebView tweaks for popups
webViewPop.setVerticalScrollBarEnabled(false);
webViewPop.setHorizontalScrollBarEnabled(false);
popSettings.setJavaScriptEnabled(true);
popSettings.setSaveFormData(true);
popSettings.setEnableSmoothTransition(true);
// Set User Agent
popSettings.setUserAgentString(userAgent + "Your App Info/Version");
// to support content re-layout for redirects
popSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
// handle new popups
webViewPop.setWebChromeClient(new CustomChromeClient());
// set the WebView as the AlertDialog.Builder’s view
builder = new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT).create();
builder.setTitle("");
builder.setView(webViewPop);
builder.setButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
webViewPop.destroy();
dialog.dismiss();
}
});
builder.show();
builder.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(webViewPop);
resultMsg.sendToTarget();
return true;
}
#Override
public void onCloseWindow(WebView window) {
//Toast.makeText(contextPop,"onCloseWindow called",Toast.LENGTH_SHORT).show();
try {
webViewPop.destroy();
} catch (Exception e) {
Log.d("Webview Destroy Error: ", e.getStackTrace().toString());
}
try {
builder.dismiss();
} catch (Exception e) {
Log.d("Builder Dismiss Error: ", e.getStackTrace().toString());
}
}
}
}
Here is the working code:
public class MainActivity extends Activity {
protected WebView mainWebView;
// private ProgressBar mProgress;
private Context mContext;
private WebView mWebviewPop;
private FrameLayout mContainer;
private ProgressBar progress;
private String url = "http://m.example.com";
private String target_url_prefix = "m.example.com";
public void onBackPressed() {
if (mainWebView.isFocused() && mainWebView.canGoBack()) {
mainWebView.goBack();
} else {
super.onBackPressed();
finish();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this.getApplicationContext();
// Get main webview
mainWebView = (WebView) findViewById(R.id.webView);
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mainWebView.setWebContentsDebuggingEnabled(true);
}
mainWebView.getSettings().setUserAgentString("example_android_app");
// Cookie manager for the webview
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
// Get outer container
mContainer = (FrameLayout) findViewById(R.id.webview_frame);
if (!InternetConnection.checkNetworkConnection(this)) {
showAlert(this, "No network found",
"Please check your internet settings.");
} else {
// Settings
WebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
mainWebView.setWebChromeClient(new MyCustomChromeClient());
mainWebView.loadUrl(url);
}
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.example_main, menu);
// return true;
// }
private class MyCustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progress.setProgress(0);
progress.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String host = Uri.parse(url).getHost();
Log.d("shouldOverrideUrlLoading", host);
//Toast.makeText(MainActivity.this, host,
//Toast.LENGTH_SHORT).show();
if (host.equals(target_url_prefix)) {
// This is my web site, so do not override; let my WebView load
// the page
if (mWebviewPop != null) {
mWebviewPop.setVisibility(View.GONE);
mContainer.removeView(mWebviewPop);
mWebviewPop = null;
}
return false;
}
if (host.contains("m.facebook.com") || host.contains("facebook.co")
|| host.contains("google.co")
|| host.contains("www.facebook.com")
|| host.contains(".google.com")
|| host.contains(".google.co")
|| host.contains("accounts.google.com")
|| host.contains("accounts.google.co.in")
|| host.contains("www.accounts.google.com")
|| host.contains("www.twitter.com")
|| host.contains("secure.payu.in")
|| host.contains("https://secure.payu.in")
|| host.contains("oauth.googleusercontent.com")
|| host.contains("content.googleapis.com")
|| host.contains("ssl.gstatic.com")) {
return false;
}
// Otherwise, the link is not for a page on my site, so launch
// another Activity that handles URLs
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//startActivity(intent);
//return true;
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
progress.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
Log.d("onReceivedSslError", "onReceivedSslError");
// super.onReceivedSslError(view, handler, error);
}
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
public void showAlert(Context context, String title, String text) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle(title);
// set dialog message
alertDialogBuilder.setMessage(text).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
finish();
}
}).create().show();
}
private class MyCustomChromeClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
mWebviewPop = new WebView(mContext);
mWebviewPop.setVerticalScrollBarEnabled(false);
mWebviewPop.setHorizontalScrollBarEnabled(false);
mWebviewPop.setWebViewClient(new MyCustomWebViewClient());
mWebviewPop.getSettings().setJavaScriptEnabled(true);
mWebviewPop.getSettings().setSavePassword(false);
mWebviewPop.setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
mContainer.addView(mWebviewPop);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(mWebviewPop);
resultMsg.sendToTarget();
return true;
}
#Override
public void onProgressChanged(WebView view, int newProgress) {
// TODO Auto-generated method stub
super.onProgressChanged(view, newProgress);
MainActivity.this.setValue(newProgress);
}
#Override
public void onCloseWindow(WebView window) {
Log.d("onCloseWindow", "called");
}
}
}
mainWebView.getSettings().setUserAgentString("example_android_app");
fixed it for me
just changed mainWebView to what my webview was called. In my case, i set it to
webView.getSettings().setUserAgentString("example_android_app");
I need a progress bar at the centre of my android webview it must be shown before the page loads and hides when the page is loaded. How can it be done? Can anyone help me?
This is my code for webview:
Bundle extras = getIntent().getExtras();
String title;
final String url;
if (!Datacon.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "Check your Internet Connection!", Toast.LENGTH_LONG).show();
} else {
if (extras != null) {
title = extras.getString("title");
url = extras.getString("url");
TextView text=(TextView) findViewById(R.id.textView1);
text.setText(title);
final WebView myWebView =(WebView)findViewById(R.id.WebView);
myWebView.loadUrl(url);
myWebView.getSettings().setLoadWithOverviewMode(true);
myWebView.getSettings().setUseWideViewPort(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
loadingProgressBar=(ProgressBar)findViewById(R.id.progressbar_Horizontal);
myWebView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
Button refresh = (Button) actionBar.getCustomView().findViewById(R.id.but2);
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myWebView.loadUrl(url);
}
});
}
}}
}
You need to override a couple of more methods in the WebViewClient :
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
loadingProgressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
loadingProgressBar.setVisibility(View.GONE);
}
I'm assuming loadingProgressBar is a class field.
PS: As a side note I believe you overriding shouldOverrideUrlLoading is unnecessary. The default behaviour is to load the url, as you instruct it to do.
private void initializeProgressBar() {
if (progressBar == null){
progressBar = new ProgressDialog(this);
progressBar.setMessage(Constants.LOADING_MESSAGE);
progressBar.setCancelable(false);
}
}
Handler peogressBar = new Handler(){
public void handleMessage(android.os.Message msg) {
try{
switch (msg.what) {
case 1:
initializeProgressBar();
if(!progressBar.isShowing())
progressBar.show();
break;
case 2:
if (progressBar != null && progressBar.isShowing()) {
progressBar.dismiss();
progressBar = null;
}
break;
}
}catch(Exception e){
e.printStackTrace();
}
};
};
wv_graphLink = (WebView) findViewById(R.id.wv_graphLink);
wv_graphLink.getSettings().setJavaScriptEnabled(true);
wv_graphLink.getSettings().setBuiltInZoomControls(true);
wv_graphLink.getSettings().setSupportZoom(true);
wv_graphLink.setInitialScale(1);
wv_graphLink.getSettings().setLoadWithOverviewMode(true);
wv_graphLink.getSettings().setUseWideViewPort(true);
// wv_graphLink.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
// wv_graphLink.setScrollbarFadingEnabled(false);
peogressBar.sendEmptyMessage(1);
wv_graphLink.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged(WebView view, int progress) {
if(progress == 100){
peogressBar.sendEmptyMessage(2);
}
}
});
wv_graphLink.loadUrl("Your url");
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;