Background:
* Full Stack developer training (recently finished studies).
* Am not very (putting it mildly) Java savvy.
for the past couple of days I've been trying to make the tapping on a OneSignal notification open the app according to the URL stored in the notification payload.
What did work was:
* If the app is showing on the screen and you press the notification it works fine and opens it accordingly.
It does ALMOST work in the way that if the app is in the background and you press the notification it either:
1. Launches the app but on the main page
OR
2. Doesn't launch the app but when you actively go back to the app it shows the correct content (according to the URL of the notification)
Following is the code:
Thank you!
package app.web.hodaya;
import com.onesignal.OSNotificationOpenResult;
import com.onesignal.OneSignal;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import org.json.JSONObject;
import static com.onesignal.OneSignal.sendTag;
import static com.onesignal.OneSignal.sendTags;
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
CalculateObject calcObject = new CalculateObject();
PassingStringThrough passString = new PassingStringThrough();
ExampleNotificationOpenedHandler notificationOpened = new ExampleNotificationOpenedHandler();
UpdateOneSignalSettingTags sendTag = new UpdateOneSignalSettingTags();
super.onCreate(savedInstanceState);
// OneSignal Initialization
OneSignal.startInit(this)
.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
.unsubscribeWhenNotificationsAreDisabled(true)
.setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
.init();
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://hodaya-app.firebaseapp.com/");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.addJavascriptInterface(passString, "ob1");
try {
this.getSupportActionBar().hide();
} catch (NullPointerException e) {
}
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
class PassingStringThrough {
#JavascriptInterface
public void passString(
String m, String m1, String n, String n1, String e, String e1,
String name, String name1, String gender, String gender1) {
sendTag(m, m1);
sendTag(n, n1);
sendTag(e, e1);
sendTag(name, name1);
sendTag(gender, gender1);
/* alternatively*/
// tags.put(m, m1);
// tags.put(n, n1);
// tags.put(e, e1);
// OneSignal.sendTags(tags);
Log.d("settingsPassedCorrectly", "I just got executed!" + m + m1 + n + n1 + e + e1 + name + name1 + gender + gender1);
}
}
class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
#Override
public void notificationOpened(OSNotificationOpenResult result) {
Log.i("OSNotificationPayload", "result.notification.payload.toJSONObject().toString(): " + result.notification.payload.toJSONObject().toString());
JSONObject data = result.notification.payload.additionalData;
String customKey;
if (data != null) {
customKey = data.optString("tryli", null);
// if (customKey != null)
Log.i("DeepLinkToCustomkey", "customkey set with value: " + customKey);
WebView webView1;
// setContentView(R.layout.activity_main);
webView1 = findViewById(R.id.webView);
webView1.setWebViewClient(new WebViewClient());
webView1.loadUrl(customKey);
// WebView webView = null;
}
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 am new to android, recently I developed an application which runs on WebView means in my activity I placed a webview doing the gamin activity through html,js pages by loading those to webview.
Here my request is "How to load the Interstitial Ads from the webpage files(html,js) I googled most of the suggestions related to Ionic App but my app is AndroidStudio related.
so please help
Loading an ad from WebView isn't that straightforward but could be done. So let's take the following example:
class MainActivity extends AppCompatActivity {
protected InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// load interstitial ad
mInterstitialAd = new InterstitialAd(getContext());
mInterstitialAd.setAdUnitId("YOUR_AD_ID");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
WebView browser = findViewById(R.id.webview);
browser.addJavascriptInterface(new InterceptorJavaScript(context), "Interceptor");
WebSettings webSettings = browser.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
browser.setWebViewClient(new CapturingWebViewClient());
browser.loadUrl("http://website.com");
}
/**
* This class will handle all JS events from the UI back to
* Java code and will trigger the Interstitial ad
*/
private class InterceptorJavaScript {
Context webViewContext;
/**
* Instantiate the interface and set the context
*/
InterceptorJavaScript(Context webView) {
webViewContext = webView;
}
#JavascriptInterface
#SuppressWarnings("unused")
public void startInterstitial() {
// we need to run it on the main UI thread
Handler mHandler = new Handler(Looper.getMainLooper());
mHandler.post(new Runnable() {
#Override
public void run() {
if (MainActivity.mInterstitialAd.isLoaded()) {
MainActivity.mInterstitialAd.show();
}
// preload new ad
BrowserFragment.mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
}
}
private class CapturingWebViewClient extends WebViewClient {
/**
* This method will inject the JavaScritp that will trigger
* your Java code and show the interstitial in the main UI thread
*/
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl(
"javascript:Interceptor.startInterstitial();"
);
// Attach JS event to your button so you can call the JS function. I've used jQuery just for simplicity
view.loadUrl(
"javascript:$('#btn').on('click', function(){ Interceptor.startInterstitial(); });"
);
}
}
}
hello this is the code....
import android.os.Bundle; import android.view.Window; import android.view.WindowManager;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
public class a4 extends AppCompatActivity {
AdView mAdView;
InterstitialAd mInterstitialAd;
WebView WebViewWithCSS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_a4);
WebViewWithCSS = (WebView)findViewById(R.id.webView);
WebSettings webSetting = WebViewWithCSS.getSettings();
webSetting.setJavaScriptEnabled(true);
WebViewWithCSS.setWebViewClient(new WebViewClient());
WebViewWithCSS.loadUrl("file:///android_asset/4.html");
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
mInterstitialAd = new InterstitialAd(this);
// set the ad unit ID
mInterstitialAd.setAdUnitId(getString(R.string.interstitial_full_screen));
adRequest = new AdRequest.Builder()
.build();
// Load ads into Interstitial Ads
mInterstitialAd.loadAd(adRequest);
mInterstitialAd.setAdListener(new AdListener() {
public void onAdLoaded() {
showInterstitial();
}
});
}
#Override
public void onPause() {
if (mAdView != null) {
mAdView.pause();
}
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if (mAdView != null) {
mAdView.resume();
}
}
#Override
public void onDestroy() {
if (mAdView != null) {
mAdView.destroy();
}
super.onDestroy();
}
private void showInterstitial() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
}
Basically My question is HOW CAN I POSSIBLY PUT THESE TWO CODES TOGETHER TO FUNCTION PROPERLY!!! this is killing my trying to figure it out so i'll explain in deep detail...Any help would be much appreciated!!!
i have a webpage at http://s-ka-paidbeats.com/app_tree/ourotherapps it lists a bunch of apps i have made in google play.in the webpage html i have them listed with standard links like - https://play.google.com/store/apps/details?id=com.yesorno.app.yesorno
i've created a tab in ALL the android applaications that i've made called "My Other Apps"this tab is a webview window that shows the same html page i was talking about above- http://s-ka-paidbeats.com/app_tree/ourotherapps
the problem is when a user visits the webview window in any of my android applications and clicks on any of the apps i have listed on the html webpage (https://play.google.com/store/apps/details?id=) it takes them to google play in the webview window and asks them to login to google play in the webview window (even if they are already logged in to google play on their device)... this is extremely ugly and annoying for users to face.
i want to make it so when a user visits the "my other apps" tab in any of my applications, and clicks on one of the apps in the webview window it opens the actual google play application (if google play is installed) or opens in the default browser installed on the device (if google play is not installed)
i have tried to change all the (https://play.google.com/store/apps/details?id=) links to (market://details?id=) links on the html page and then visited the webview window again in my app however this time when i click on any of the apps listed i just get a page error "page does not exist" window
i have looked into setWebViewClient and i am sure that there is someway to do this using something like the code posted below
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getScheme().equals("market")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
Activity host = (Activity) view.getContext();
host.startActivity(intent);
return true;
} catch (ActivityNotFoundException e) {
// Google Play app is not installed, you may want to open the app store link
Uri uri = Uri.parse(url);
view.loadUrl("http://play.google.com/store/apps/" + uri.getHost() + "?" + uri.getQuery());
return false;
}
}
return false;
} });
I tried adding the code above to my current code but now my loading dialog box wont close when the webview is loading.... it just stays loading forever.... so i took the code snippet above out of my code again because i dont think i am placing it in the right place or that i am integrating the two codes together properly....
i noticed my current code already has a setWebViewClient defined so im not sure if im allowed to have two in the same code or if i am suppose to try and combine it with the current one....... I HAVE NO CLUE where to begin and i have been reading for hours....
Here is my current code
package com.yesorno.app.yesorno;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
import com.yesorno.app.yesorno.NetorkConnection;
#SuppressLint("SetJavaScriptEnabled")
public class OtherApps extends AppCompatActivity {
private WebView webView;
NetorkConnection ntwrk_con = new NetorkConnection(this);
ProgressDialog dialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView toolsresources5 = (TextView)findViewById(R.id.feedbacktextview);
toolsresources5.setVisibility(View.INVISIBLE);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
webView = (WebView) findViewById(R.id.activity_main_webview);
dialog = new ProgressDialog(OtherApps.this);
if (ntwrk_con.isConnectingToInternet()) {
webView();
} else {
dialog_box_for_internet();
}
}
public void dialog_box_for_internet() {
if (ntwrk_con.isConnectingToInternet()) {
webView();
} else {
// dismis_dialog_box_for_internet = true;
AlertDialog.Builder builder = new AlertDialog.Builder(
OtherApps.this);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_custom_titile, null);
TextView title = (TextView) view.findViewById(R.id.myTitle);
title.setText("Unable To Connect");
builder.setCustomTitle(view);
builder.setMessage("No Internet Connection")
.setCancelable(false)
.setPositiveButton("Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
if (ntwrk_con.isConnectingToInternet()) {
webView();
} else {
new Thread_for_internet().execute();
}
// dialog.cancel();
}
})
.setNegativeButton("Okay",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
finish();
// Gridview.super.onBackPressed();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
class Thread_for_internet extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Loading..Please wait.");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected Boolean doInBackground(String... args) {
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Boolean result) {
dialog.dismiss();
dialog_box_for_internet();
}
}
public void webView() {
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
});
dialog.setMessage("Loading All Our Apps...\nPlease wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
webView.loadUrl("http://s-ka-paidbeats.com/app_tree/ourotherapps.html");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean bRet=false;//set true is menu selection handled
switch (item.getItemId()) {
case R.id.action_settings_3:
Toast.makeText(this, Html.fromHtml("<big><b>Develeped By S-Ka-Paid</b></big><br>© 2016 S-Ka-Paid"), Toast.LENGTH_LONG).show();
bRet=true;
break;
case R.id.action_settings_4:
Intent intent2 = new Intent(Intent.ACTION_VIEW);
//Try Google play
intent2.setData(Uri.parse("market://details?id=com.yesorno.app.yesorno"));
startActivity(intent2);
bRet=true;
break;
default:
bRet=super.onOptionsItemSelected(item);
}
return bRet;
} }
Basically My question is HOW CAN I POSSIBLY PUT THESE TWO CODES TOGETHER TO FUNCTION PROPERLY!!! this is killing my trying to figure it outAny help would be much appreciated!!!
i have tried to change all the (https://play.google.com/store/apps/details?id=) links to (market://details?id=) links on the html page
Don't do that. Use the google play URLs you started with.
i noticed my current code already has a setWebViewClient defined so im not sure if im allowed to have two in the same code or if i am suppose to try and combine it with the current one
You combine them. You create one WebViewClient to handle all the needs of one WebView. It's not difficult:
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// is this a play store URL?
String partialUrl = "/store/apps/details?id=";
if (url.contains(partialUrl)) {
// extract the app id from the URL
int pos = url.indexOf(partialUrl) + partialUrl.length();
String appId = url.substring(pos);
try {
// open the google play app
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=" + appId));
OtherApps.this.startActivity(intent);
return true; // we overrode the url load
} catch (ActivityNotFoundException e) {
// no google play app, load URL in device browser
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
OtherApps.this.startActivity(intent);
return true;
}
}
return false; // no override, let the webview load this url
}
});
for anyone looking for the answer to this... here is the correct code
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// is this a play store URL?
String partialUrl = "/store/apps/details?id=";
if (url.contains(partialUrl)) {
// extract the app id from the URL
int pos = url.indexOf(partialUrl) + partialUrl.length();
String appId = url.substring(pos);
try {
// open the google play app
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=" + appId));
OtherApps.this.startActivity(intent);
return true; // we overrode the url load
} catch (ActivityNotFoundException e) {
// no google play app, load URL in device browser
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
OtherApps.this.startActivity(intent);
return true;
}
}
return false; // no override, let the webview load this url
}
});
I am trying to login to a webpage using Javascript for my app but after successful login I want to load a page which will display the ExamSeatingPlan. The app is working fine its loading the required page after successful login but its almost taking 80% of CPU. I think I didn't implement onPageFinished right.It will be really helpful if you guys help me solve the problem
Thanks.
MainActivity.java
package com.example.ebad.badwae;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
final String url = "http://111.68.99.8/StudentProfile/";
final String urlwanttoload = "http://111.68.99.8/StudentProfile/ExamSeatingPlan.aspx";
WebView view;
boolean loaded;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (WebView) findViewById(R.id.webview);
WebSettings webSettings = view.getSettings();
webSettings.setJavaScriptEnabled(true);
view.loadUrl(url);
view.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView views, String urls) {
view.loadUrl("javascript: {" + "document.getElementById('ctl00_Body_ENROLLMENTTextBox_tb').value = '" + "01-134121-061" + "';" +
"document.getElementById('ctl00_Body_PasswordTextBox_tb').value = '" + "123456789" + "';" +
"document.getElementsByName('ctl00$Body$LoginButton')[0].click();" + "};");
onPageFinishede(views, urls);
}
public void onPageFinishede(WebView views, String urls) {
if (!loaded) {
views.loadUrl(urlwanttoload);
loaded = true;
}
}
});
}
}
I am developing android web application for a blog like website.
For this I am showing HTML page contenting list of categories which when clicked shows articles related to that category.
I am fetching this articles from website's RSS feeds which is in XML format and by using JavaScript I am parsing it to display on HTML page.
This process of parsing XML takes lot of time to load a page.During this period I am getting blank screen.I have implemented progress dialog which works fine when page is loading for the first time but when XML is getting parsed by JavaScript it does not appear.
Here is how I implemented Process dialog.
Activity.java:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.setBackgroundColor(0);
final ProgressDialog progressDialog = new ProgressDialog(activity);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...please wait");
progressDialog.setCancelable(true);
webview.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webview.loadUrl("file:///android_asset/HomePage.html");
// WebChromeClient give progress etc info
webview.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view, int progress)
{
progressDialog.show();
progressDialog.setProgress(0);
activity.setProgress(progress * 1000);
progressDialog.incrementProgressBy(progress);
if (progress == 100 && progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
How can I show progress dialog while XML is being parsed by JavaScript?
Also I want to show an error message if no internet connectivity available for same thing is their any way to do so?
I have used call function as "tel:phone number" which was working but after I added de
public boolean shouldOverrideUrlLoading it is not working? what's i done wrong?
for your questions You can use following code in your activity.java file
package com.package name;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;
public class Myactivity extends Activity {
TextView myLabel;
WebView wv;
final Activity activity=this;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,Window.PROGRESS_VISIBILITY_ON);
wv=(WebView)findViewById(R.id.webview);
wv.getSettings().setJavaScriptEnabled(true);
wv.setBackgroundColor(0);
final ProgressDialog progressDialog = new ProgressDialog(activity);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...please wait");
progressDialog.setCancelable(true);
wv.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL,
Uri.parse(url));
startActivity(intent);
return true;
}else{
view.loadUrl(url);
return true;
}
}
});
wv.loadUrl("file:///android_asset/page.html");
// WebChromeClient give progress etc info
wv.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view, int progress)
{
progressDialog.show();
progressDialog.setProgress(0);
activity.setProgress(progress * 1000);
progressDialog.incrementProgressBy(progress);
if (progress == 100 && progressDialog.isShowing())
progressDialog.dismiss();
}
});
if (AppStatus.getInstance(this).isOnline(this)) {
Toast t = Toast.makeText(this,"Welcome !!!!",8000);
t.show();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(
CafeNashikActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("No Internet");
// Setting Dialog Message
alertDialog.setMessage("Internet Connection not available!");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyActivity.this.finish();
}
});
// Showing Alert Message
alertDialog.show();
}
}
}
Hope this will help you.