I got an issue. When i set view.loadUrl("http://mysite"); and trying to login, app doesn't handle the session, and shows that I'm not logged in, but when I'm setting up view.loadUrl("http://google.com"); and loading my site via google search, the session is establishing correct, other site logins view.loadUrl("http://othersite") logging fine too;
Please help, I tried anything but nothing helps... Thank you.
P.S site works well in other browsers.
my xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.FrameLayout xmlns:android="http://schemas.android.com /apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.gtr.rox.MainActivity"
android:background="#333333"
android:id="#+id/webview_frame">
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/webView"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</android.widget.FrameLayout>
Main activity
public class MainActivity extends AppCompatActivity {
private WebView mWebviewPop;
private WebView view;
private FrameLayout mContainer;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
view = (WebView) this.findViewById(R.id.webView);
mContainer = (FrameLayout) findViewById(R.id.webview_frame);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setUserAgentString("Mozilla/5.0 (Linux; Android 4.4.2; ZTE T221 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.85 Mobile Safari/537.36");
view.getSettings().setAppCacheEnabled(true);
view.getSettings().setLoadWithOverviewMode(true);
view.getSettings().setUseWideViewPort(true);
view.getSettings().setDatabaseEnabled(true);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.getSettings().setSupportMultipleWindows(true);
view.getSettings().setAllowFileAccess(true);
view.getSettings().setDomStorageEnabled(true);
view.invalidate();
view.setWebViewClient(new MyBrowser() {
});
view.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
view.loadUrl("http://mysite");
view.setWebChromeClient(new UriChromeClient() {
});
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 18);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 1);
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.apply();
}
mContext=this.getApplicationContext();
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mailto:") || url.startsWith("mms:") || url.startsWith("mmsto:") || url.startsWith("market:") || url.startsWith("https://youtu")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
} else {
view.loadUrl(url);
return true;
}
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
Log.d("onReceivedSslError", "onReceivedSslError");
//super.onReceivedSslError(view, handler, error);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && view.canGoBack()) {
view.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
class UriChromeClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
mWebviewPop = new WebView(mContext);
mWebviewPop.setVerticalScrollBarEnabled(false);
mWebviewPop.getSettings().setLoadWithOverviewMode(true);
mWebviewPop.getSettings().setUseWideViewPort(true);
mWebviewPop.setHorizontalScrollBarEnabled(false);
mWebviewPop.setWebViewClient(new MyBrowser());
mWebviewPop.getSettings().setDatabaseEnabled(true);
mWebviewPop.getSettings().setJavaScriptEnabled(true);
mWebviewPop.getSettings().setSavePassword(true);
mWebviewPop.getSettings().setAppCacheEnabled(true);
mWebviewPop.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebviewPop.getSettings().setSupportMultipleWindows(true);
mWebviewPop.getSettings().setAllowFileAccess(true);
mWebviewPop.getSettings().setDomStorageEnabled(true);
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 onCloseWindow(WebView window) {
Log.d("onCloseWindow", "called");
}
}
}
Solved by remove this line
view.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
And it works!
Related
I am trying to auth google user in WebView, I found a good solution for these days, it works fine for google login, but I cannot disable dialog in other urls like (, sms: , smsto:)
Example Situation: User click on telephone number in my app, it will open the phone dial, but when he returns back.. there is a empty dialog window with close button, i use it for google login with JS.
How can i close this dialog message inside the shouldOverrideUrlLoading()? Or is there any better solution to not open other links in the dialog? How can i improve my code to solve my problem? Thank you guys!
package com.example.app;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslCertificate;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.lang.reflect.Field;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class MainActivity extends Activity {
private WebView mWebView;
private String userAgent;
private Context contextPop;
private WebView webViewPop;
private AlertDialog builder;
#Override
#SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userAgent = System.getProperty("http.agent");
mWebView = findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setAppCacheEnabled(false);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
webSettings.setUserAgentString(userAgent+ "com.example.app");
mWebView.clearCache(true);
// REMOTE RESOURCE
mWebView.loadUrl("https://example.eu/");
mWebView.setWebChromeClient(new CustomChromeClient());
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
contextPop = this.getApplicationContext();
// LOCAL RESOURCE
// mWebView.loadUrl("file:///android_asset/index.html");
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
final Context myApp = this;
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) {
String host = Uri.parse(url).getHost();
if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mms:") || url.startsWith("mmsto:"))
{
webViewPop.destroy();
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
startActivity(intent);
return true;
}
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//view.getContext().startActivity(intent);
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(mWebView, 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());
}
}
#Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
new AlertDialog.Builder(myApp)
.setMessage(message)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
result.cancel();
}
})
.setCancelable(false)
.create()
.show();
return true;
}
#Override
public boolean onJsAlert(WebView view, final String url, String message,
JsResult result) {
new AlertDialog.Builder(myApp)
.setMessage(message)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}
})
.setCancelable(false)
.show();
result.cancel();
return true;
}
}
}
I'm new to Android studio.
So I have been writing some code that helps my job.
When the imgView and Layout clicked the app will go into WebView
On the WebView they will fill the form, after that the web should automatically downloading the .pdf file.
When I Opened it with chrome, chrome will make a new tab/pop up with some link that triggers downloading files.
How this webView could download the pdf file too? because When I opened it on the Web View, the WebView will go back to previous activity.
public class biling extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biling);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED) {
Log.d("permission", "permission denied to WRITE_EXTERNAL_STORAGE - requesting it");
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, 1);
}
}
webView = findViewById(R.id.bilingweb);
webView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading (WebView view, String url) {
if (url.endsWith(".pdf")) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
// if want to download pdf manually create AsyncTask here
// and download file
return true;
}
return false;
}
});
webView.loadUrl("https://sse2.pajak.go.id");
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.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading File...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}});
webView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus()){
v.requestFocus();
}
break;
}
return false;
}
});
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowContentAccess(true);
webSettings.setAllowFileAccess(true);
webSettings.setDisplayZoomControls(true);
webSettings.setAllowFileAccess(true);
webSettings.setSupportMultipleWindows(true);
Toolbar toolbar = findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("e-Biling");
getSupportActionBar().setSubtitle("Bayar Pajak Online");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
if (webView.canGoBack()){webView.goBack();}
else
{super.onBackPressed();}
}
}
I have two webviews in my android app one webview deletes content based on given javascript function and other one is remaining same even I give javascript function by id. The main webview working perfectly and other one not and now i may integrating another webview if my second webview works perfectly.
here is my first webview it's working perfectly
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new myWebClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("url");
webView.getSettings().setDomStorageEnabled(true)
public class myWebClient extends WebViewClient
{
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:(function() {document.getElementById('mainHeader').style.display='none';" + "document.getElementById('footerRights').style.display='none';" + "document.getElementById('navTrail').style.display='none';" + "document.getElementById('threeColumns').style.display='none';" + " })()");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
}
#Override
// This method is used to detect back button
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}
my second webview
public class webview2 extends AppCompatActivity {
private WebView webVIEW;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
webVIEW = (WebView) findViewById(R.id.webVIEW);
webVIEW.setWebViewClient(new WebViewClient());
webVIEW.getSettings().setJavaScriptEnabled(true);
webVIEW.loadUrl("example url");
webVIEW.getSettings().setJavaScriptEnabled(true);
webVIEW.getSettings().setDomStorageEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public class webVIEW extends WebViewClient {
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:(function() { " + "var element = document.getElementById('hplogo');" + "element.parentNode.removeChild(element);" + " })()");
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon ) {
super.onPageStarted(view, url, favicon);
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed(){
if (webVIEW.canGoBack()) {
webVIEW.goBack();
}else {
super.onBackPressed();
}
}
}
webview2.java
its being remaining same no javascript excution now i need to integrate another webview and it also needs the same as first webview
Thanks in Advance
I have solved my question using kotlin class by this i can inject java script in one or more webviews
class webview2 : AppCompatActivity() {
private lateinit var webVIEW: WebView
#SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_webview)
webVIEW = findViewById<WebView>(R.id.webVIEW) as WebView
webVIEW.settings.javaScriptEnabled = true
webVIEW.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
injectJS()
}
}
webVIEW.loadUrl("https://example/login")
}
val progressBar = findViewById<ProgressBar>(R.id.progressBar3)
override fun onBackPressed() {
if (webVIEW.canGoBack()) {
webVIEW.goBack();
} else {
super.onBackPressed()
}
}
private fun injectJS() {
val jsContent: String?
jsContent = try {
val inputStream = assets.open("style.js")
val fileContent = inputStream.bufferedReader().use(BufferedReader::readText)
inputStream.close()
fileContent
} catch (e: Exception) {
null
}
jsContent?.let { webVIEW.loadUrl("javascript:($jsContent)()") }
}
}
I'm trying to make the javascript work in android for this page:
http://test.swiss-impulse.com/scratch_card_game/index.html
But i have issues regarding the browser.
This is the parameters set for the webview:
webView1.setWebChromeClient(mClient);
webView1.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
webView1.addJavascriptInterface(new JavaScriptInterfaceForTitle(this, mPasswordStrength, webView1), "HtmlViewer");
webView1.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
String cookie = CookieManager.getInstance().getCookie(url);
if (url.equals(getContentUrl() + "addcomment")) {
webView1.stopLoading();
Intent addcommentIntent = new Intent(mContext, AddCommentActivity.class);
addcommentIntent.putExtra("url", previousUrl);
startActivity(addcommentIntent);
} else {
previousUrl = url;
((BaseActivity) mContext).showLoadingDialog();
if (!urlStackList.contains(url)) {
urlStackList.add(url);
}
super.onPageStarted(view, url, favicon);
}
}
#Override
public void onPageFinished(WebView view, String url) {
((BaseActivity) mContext).hideLoadingDialog();
if (url.contains("content/shows/") || url.contains("content/tips/")) {
counter = 0;
view.loadUrl("javascript:window.HtmlViewer.showHTML(document.getElementById('" + mContext.getString(R.string.title_name) + "').innerHTML);");
view.loadUrl("javascript:window.HtmlViewer.showHTML(document.getElementById('name_en').innerHTML);");
view.loadUrl("javascript:window.HtmlViewer.showHTML(document.getElementById('name_zh').innerHTML);");
} else {
mStateBar.setShowTitle(mContext.getString(R.string.tv_drama));
}
super.onPageFinished(view, url);
}
});
webview1.setWebChromeClient(mClient);
webView1.getSettings().setJavaScriptEnabled(true);
webView1.getSettings().setPluginState(PluginState.ON);
webView1.getSettings().setPluginsEnabled(true);
webView1.getSettings().setAppCacheMaxSize(httpCacheSize);
webView1.getSettings().setSupportZoom(false);
webView1.getSettings().setBuiltInZoomControls(false);
webView1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
Am i missing some parameters to make this work on android webview ? I checked chrome browser and there it works with no problems, so i'm sure i missed something and cannot find what.
EDIT:
class MyChromeClient extends WebChromeClient {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
mCustomViewCallback = callback;
mTargetView.addView(view);
mCustomView = view;
mContentView.setVisibility(View.GONE);
mTargetView.setVisibility(View.VISIBLE);
mTargetView.bringToFront();
}
#Override
public void onHideCustomView() {
if (mCustomView == null)
return;
mCustomView.setVisibility(View.GONE);
mTargetView.removeView(mCustomView);
mCustomView = null;
mTargetView.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
mContentView.setVisibility(View.VISIBLE);
}
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
TvDramaActivity.this.startActivityForResult(Intent.createChooser(i, "Chooser"), 100);
}
// For Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
// For Android > 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, "");
}
#Override
public void onProgressChanged(WebView view, int newProgress) {
}
}
public boolean inCustomView() {
return (mCustomView != null);
}
public void hideCustomView() {
mClient.onHideCustomView();
}
This works for me :
In your WebView Activity class :
WebView webView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView1 = (WebView) findViewById(R.id.web);
webView1.setWebChromeClient(new WebChromeClient());
webView1.getSettings().setJavaScriptEnabled(true);
webView1.getSettings().setPluginState(PluginState.ON);
webView1.getSettings().setSupportZoom(false);
webView1.getSettings().setBuiltInZoomControls(false);
webView1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView1.loadUrl("http://test.swiss-impulse.com/scratch_card_game/index.html");
}
Your layout file :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/web"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
Don't forget to add <uses-permission android:name="android.permission.INTERNET"/> in manifest file.
Hope this helps.Thanks.
you can try below code
mWebView.setWebChromeClient(new WebChromeClient());
//support JavaScript
mWebView.getSettings().setJavaScriptEnabled(true);
I am not able to call web service or no alert is being shown:
my activity code:
mWebView = (WebView)findViewById(R.id.webViewRootAciviy);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.loadUrl("file:///android_asset/splashscreen.html");
html code:
<html>
<body>
this is a demo html file.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js">
$.ajax({
type: 'GET',
url: 'http://192.168.11.50/ar/service.svc/ProductCategories?$format=json',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data)
{
alert("success");
},
error: function (error)
{
alert("error");
}
});
</script>
</body>
</html>
Also given the Internet permission. Please help me find what i missed.
Edit:
We have our own server in our company and service is hosted on it. I am using wifi to access internet and server is also connected to the same wifi router with ethernet cable.
Update: I dont know why this happened. The problem was arised due to the type of service created. The web service was created using WCF Data service, but after creating web service again using normal WCF Service, the URL is working fine now.
apply this to your webview.
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
} else {
return false;
}
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(give your url);
// I used this class and my code is working fime at my side please try this may be it will help you
public class WebViewActivity extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
private TextView header_maintext;
private TextView headeroptiontext;
private RelativeLayout back;
private String url_string="http://www.google.com";
private String header_maintext_string="Your text";
/** Called when the activity is first created. */
#SuppressLint("SetJavaScriptEnabled") #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.webview_layout);
webview = (WebView)findViewById(R.id.webview01);
header_maintext= (TextView)findViewById(R.id.header_maintext);
header_maintext.setText(header_maintext_string);
headeroptiontext = (TextView)findViewById(R.id.headeroptiontext);
headeroptiontext.setVisibility(View.GONE);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
back = (RelativeLayout) findViewById(R.id.back_layout);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(webview.canGoBack() == true)
{
webview.goBack();
}
else
{
finish();
}
}
});
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(WebViewActivity.this, "My application", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(WebViewActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
webview.loadUrl(url_string);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack() == true){
webview.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}