I have a webview, yes i do. :)
Anyway, I load my main URL fine, but i need to load another url programmatically at some point. The problem is that it somewhat opens another webview, and I know this because when I exit the app using finish() method, the webview with the latter url closes, but another webview stays open. What should I do? Should i call destroy webview or something else?
I just load them URLs using webview.loadUrl(url here) method.
Here's what's inside my main activity:
package com.sample;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
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.content.pm.ActivityInfo;
import android.graphics.Bitmap;
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.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity
{
private WebView wv;
private ProgressBar progress;
private static String mycaturl="*url 1*";
private static String helpurl="*url 2*";
private static String fbackurl="*url 3*";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
if (reachable(this))
{
Toast.makeText(this, "Reachable", Toast.LENGTH_SHORT).show();
buildwv( savedInstanceState, WebSettings.LOAD_DEFAULT, mycaturl );
}
else
{
Toast.makeText(this, "Unreachable", Toast.LENGTH_SHORT).show();
eolc( savedInstanceState );
}
}
#SuppressLint({ "SetJavaScriptEnabled" })
public void buildwv(Bundle sis, int load, String url)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
setContentView(R.layout.activity_main);
//assigning objects to variables
wv=(WebView) findViewById(R.id.wv);
wv.setWebViewClient( new wvc() );
progress=(ProgressBar) findViewById(R.id.progress);
//websettings
WebSettings ws = wv.getSettings();
ws.setAppCacheMaxSize( 100 * 1024 * 1024 ); // 100MB
ws.setAppCachePath( this.getCacheDir().getAbsolutePath() );
ws.setAllowFileAccess( true );
ws.setAppCacheEnabled( true );
ws.setJavaScriptEnabled( true );
ws.setCacheMode(load);
//if instance is saved, to catch orientation change
if(sis==null)
{ wv.loadUrl(url); }
}
public void eolc(final Bundle sis)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
AlertDialog.Builder alertDialog = new AlertDialog.Builder( MainActivity.this );
alertDialog.setTitle("Unreachable Host");
alertDialog.setMessage("Host is unreachable. Load from cache or exit.");
alertDialog.setIcon(R.drawable.tick);
//alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton( "Load from Cache", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to load cache.", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, mycaturl );
}
});
alertDialog.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help. EOLC", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, helpurl );
}
});
alertDialog.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.create();
alertDialog.show();
}
public void roe()
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
AlertDialog.Builder alertDialog = new AlertDialog.Builder( MainActivity.this );
alertDialog.setTitle("Connection Lost");
alertDialog.setMessage("Connection to host was lost. Restart and load cache or exit.");
alertDialog.setIcon(R.drawable.tick);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton( "Restart", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
Toast.makeText(getApplicationContext(), "You chose to restart and load cache.", Toast.LENGTH_SHORT).show();
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity(i);
}
});
alertDialog.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help. ROE", Toast.LENGTH_SHORT).show();
wv.stopLoading();
wv.loadUrl( helpurl );
}
});
alertDialog.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose to exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.create();
alertDialog.show();
}
private class wvc extends WebViewClient
{
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
progress.setVisibility(View.VISIBLE);
if (url.contains(mycaturl))
{
WebSettings ws = wv.getSettings();
if ( !reachable(getApplicationContext()) )
{
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
roe();
}
else if ( ws.getCacheMode() == WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(), "loading cache coz not reachable", Toast.LENGTH_SHORT).show();
}
}
else
{
if ( ws.getCacheMode() == WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(), "Connection to server established.", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
Toast.makeText(getApplicationContext(), "PAGE DONE LOADING!!", Toast.LENGTH_SHORT).show();
//circular progress bar close
progress.setVisibility(View.GONE);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
super.onReceivedError(view, errorCode, description, failingUrl);
wv.stopLoading();
WebSettings ws = wv.getSettings();
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
wv.loadUrl(helpurl);
Toast.makeText(getApplicationContext(), "Page unavailable", Toast.LENGTH_SHORT).show();
}
else
{
wv.loadUrl(helpurl);
Toast.makeText(getApplicationContext(), "Page not cached", Toast.LENGTH_SHORT).show();
}
roe();
}
}
//checking connectivity by checking if site is reachable
public static boolean reachable(Context context)
{
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
try
{
URL url = new URL(mycaturl);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(5000); // five seconds timeout in milliseconds
urlc.connect();
if (urlc.getResponseCode() == 200) // good response
{ return true; } else { return false; }
}
catch (IOException e)
{ return false; }
}
else
{ return false; }
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onBackPressed ()
{
if (wv.isFocused() && wv.canGoBack())
{ wv.goBack(); } else { finish(); }
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.item1:
wv.loadUrl( helpurl );
break;
case R.id.item2:
wv.loadUrl( fbackurl );
break;
case R.id.item3:
String currurl=wv.getUrl();
wv.loadUrl(currurl);
break;
case R.id.item4:
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
break;
case R.id.item5:
finish();
break;
default:
break;
}
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState )
{
super.onSaveInstanceState(outState);
wv.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
wv.restoreState(savedInstanceState);
}
}
Should I also include manifest? Thanks in advance.
Put this in your web Activity :
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Then set :
your_webview.setWebViewClient(new MyWebViewClient());
Hope this will help you
Without the necessary code I have to assume this is what you need to add to your implementation.
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
webview.loadUrl(url);
return true;
}
Related
I'm having a problem with my WebView-App.
I want to add a "Connection-check" on startup that's popping up an error when no Internet-connection is aviable or the WebView is timed out. I can't get it done by myself because I'm new in Android-programming.
I also want to add an options-menu where i can reload the actual page.
Hope someone can help me...
The actual code:
package com.sabithpkcmnr.webviewmaster;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ImageView superImageView;
ProgressBar superProgressBar;
WebView superWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayShowHomeEnabled(true);
superImageView = findViewById(R.id.myImageView);
superProgressBar = findViewById(R.id.myProgressBar);
superWebView = findViewById(R.id.myWebView);
superProgressBar.setMax(100);
superWebView.loadUrl("http://google.com");
superWebView.getSettings().setJavaScriptEnabled(true);
superWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
});
superWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
superProgressBar.setProgress(newProgress);
}
#Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
getSupportActionBar().setTitle(title);
}
#Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
superImageView.setImageBitmap(icon);
}
});
superWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Uri myUri = Uri.parse(url);
Intent superIntent = new Intent(Intent.ACTION_VIEW);
superIntent.setData(myUri);
startActivity(superIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater myMenuInflater = getMenuInflater();
myMenuInflater.inflate(R.menu.super_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.myMenuOne:
onBackPressed();
break;
case R.id.myMenuTwo:
GoForward();
break;
case R.id.myMenuThree:
break;
}
return true;
}
private void GoForward() {
if (superWebView.canGoForward()) {
superWebView.goForward();
} else {
Toast.makeText(this, "Can't go further!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
if (superWebView.canGoBack()) {
superWebView.goBack();
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("(Exit?");
dialog.setMessage("Name has nothing to go back, so what next?");
dialog.setPositiveButton("EXIT ME", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.setCancelable(false);
dialog.setNegativeButton("STAY HERE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
}
Try below method by replacing your setWebViewClient,
superWebView= (WebView) findViewById(R.id.webView);
superWebView.setWebViewClient(new myWebClient());
superWebView.getSettings().setJavaScriptEnabled(true);
superWebView.loadUrl("LOAD_YOUR_URL");
superWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
try {
webView.stopLoading();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(webView, errorCode, description, failingUrl);
}
});
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Below method can be used to check internet connection.
public static boolean checkInternetConnection(Context context) {
ConnectivityManager con_manager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
return (con_manager.getActiveNetworkInfo() != null
&& con_manager.getActiveNetworkInfo().isAvailable()
&& con_manager.getActiveNetworkInfo().isConnected());
}
you can check internet connection before loading url in webview.
Check below code snippet.
if (checkInternetConnection(this)) {
superWebView.loadUrl("http://google.com");
}else{
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
}
i have a webview in which i want to add the functionality of changing the homepage through edit text field. like all the browsers do, but from other activity (i want to have this and all the other settings in another activity). is it possible to do so? Thanks
package com.example.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
private WebView webView;
private EditText urlEditText;
private ProgressBar progress;
private ToggleButton getToggleButton(int id) {
return (ToggleButton) findViewById(id);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getToggleButton(R.id.leave_toggle).setOnCheckedChangeListener(
new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton toggleButton,
boolean isChecked) {
if (isChecked) {
webView.getSettings().setLoadsImagesAutomatically(
false);// Enable Image
// Loading
} else {
webView.getSettings().setLoadsImagesAutomatically(
true);// Enable Image
// Loading
}
}
});
urlEditText = (EditText) findViewById(R.id.urlField);
webView = (WebView) findViewById(R.id.webView);
webView.setWebChromeClient(new MyWebViewClient());
webView.setDownloadListener(new DownloadListener() {// Download Manager
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
CookieManager.getInstance().setAcceptCookie(true);// Enable Cookies
webView.getSettings().setJavaScriptEnabled(true);// Enable Java Script
webView.setWebViewClient(new HelloWebViewClient());
webView.loadUrl("http://www.google.com/"); // Set
// Home
// page
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);// Remove
// ScrollBars
webView.getSettings().setDefaultFontSize(12);// Set Font Size
webView.getSettings().setPluginState(PluginState.ON);// Enable Flash
webView.setBackgroundColor(0x00000000);// Transparent Screen When
// Loading
webView.getSettings().setBuiltInZoomControls(true);// Set Zoom
// Controls
webView.requestFocus(View.FOCUS_DOWN);// Enable WebView Interaction
webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);// Set Cache
// (8mb)
String appCachePath = getApplicationContext().getCacheDir()
.getAbsolutePath();// Set Cache (8mb)
webView.getSettings().setAppCachePath(appCachePath);// Set Cache (8mb)
webView.getSettings().setAllowFileAccess(true);// Set Cache (8mb)
webView.getSettings().setAppCacheEnabled(true);// Set Cache (8mb)
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);// Set
// Cache
// (8mb)
webView.setWebViewClient(new WebViewClient() {// Open URL on Error
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {// Open URL on Error
Intent intent = new Intent(MainActivity.this, Error.class);
startActivity(intent);
}
});
// ////8888888888888888**URL BAR AND PROGRESS
// BAR**888888888888888888888888888888888
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
Button openUrl = (Button) findViewById(R.id.goButton);
openUrl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String url = urlEditText.getText().toString();
if (url.endsWith(".ac") || url.endsWith(".ac.uk")
if (!url.startsWith("http://")
&& !url.startsWith("https://")) {
url = "http://" + url;
}
}
if (validateUrl(url)) {
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
MainActivity.this.progress.setProgress(10);
}
}
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);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
// ////8888888888888888**URL BAR AND PROGRESS
// BAR**888888888888888888888888888888888
class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url) {
webview.loadUrl(url);
return true;
}
}
public void forward(View view) { // Forward Button
Toast toast = Toast.makeText(this, "Forward", Toast.LENGTH_LONG);
toast.show();
webView.goForward();
}
public void back(View view) { // Back Button
Toast toast = Toast.makeText(this, "Back", Toast.LENGTH_LONG);
toast.show();
webView.goBack();
}
public void stop(View view) { // Stop Button
Toast toast = Toast.makeText(this, "Stop", Toast.LENGTH_LONG);
toast.show();
webView.stopLoading();
}
public void reload(View view) { // Reload Button
Toast toast = Toast.makeText(this, "Reloading..", Toast.LENGTH_LONG);
toast.show();
webView.reload();
}
// Tools navigation
public void database(View view) {
Intent intent = new Intent(this, Edt_Txt.class);
Toast toast = Toast.makeText(this, "Memory", Toast.LENGTH_LONG);
toast.show();
startActivity(intent);
}
public void mini(View view) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Toast toast = Toast.makeText(this, "Minimized", Toast.LENGTH_LONG);
toast.show();
startActivity(startMain);
}
public void json(View view) {
Intent intent = new Intent(this, JSON.class);
Toast toast = Toast.makeText(this, "Loading JSON (BETA)",
Toast.LENGTH_LONG);
toast.show();
startActivity(intent);
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
finish();
System.exit(0);
}
}).setNegativeButton("No", null).show();
}
}
This is code below when u click to set default url as home page :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("URL","http"//sample.com");
editor.apply();
When u set url to browser do this :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String url= preferences.getString("URL","");
if(!name.equalsIgnoreCase(""))
{
//set url in broswer u will always get as last setted home page url
}
Basic question, what did i do? Hahaha. What did i do to make url load inside webview?
At first i overridden shouldOverrideUrlLoading to control where the link loads, then i one time i removed it but url still loads inside webview. And now i need to once again override url loading because i need a link to be opened on the default browser, but i don't know how. I even tried what others suggested to force url loading on the default browser, but it doesn't work. Please help me. Here's my code:
package com.sample;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
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.content.pm.ActivityInfo;
import android.graphics.Bitmap;
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.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity
{
private WebView wv;
private ProgressBar progress;
private static String mycaturl="*url 1*";
private static String helpurl="*url 2*";
private static String fbackurl="*url 3*";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
if (reachable(this))
{
Toast.makeText(this, "Reachable", Toast.LENGTH_SHORT).show();
buildwv( savedInstanceState, WebSettings.LOAD_DEFAULT, mycaturl );
}
else
{
Toast.makeText(this, "Unreachable", Toast.LENGTH_SHORT).show();
eolc( savedInstanceState );
}
}
#SuppressLint({ "SetJavaScriptEnabled" })
public void buildwv(Bundle sis, int load, String url)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
setContentView(R.layout.activity_main);
//assigning objects to variables
wv=(WebView) findViewById(R.id.wv);
wv.setWebViewClient( new wvc() );
progress=(ProgressBar) findViewById(R.id.progress);
//websettings
WebSettings ws = wv.getSettings();
ws.setAppCacheMaxSize( 100 * 1024 * 1024 ); // 100MB
ws.setAppCachePath( this.getCacheDir().getAbsolutePath() );
ws.setAllowFileAccess( true );
ws.setAppCacheEnabled( true );
ws.setJavaScriptEnabled( true );
ws.setCacheMode(load);
//if instance is saved, to catch orientation change
if(sis==null)
{ wv.loadUrl(url); }
}
public void eolc(final Bundle sis)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
AlertDialog.Builder alertDialog = new AlertDialog.Builder( MainActivity.this );
alertDialog.setTitle("Unreachable Host");
alertDialog.setMessage("Host is unreachable. Load from cache or exit.");
alertDialog.setIcon(R.drawable.tick);
//alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton( "Load from Cache", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to load cache.", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, mycaturl );
}
});
alertDialog.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help. EOLC", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, helpurl );
}
});
alertDialog.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.create();
alertDialog.show();
}
public void roe()
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
AlertDialog.Builder alertDialog = new AlertDialog.Builder( MainActivity.this );
alertDialog.setTitle("Connection Lost");
alertDialog.setMessage("Connection to host was lost. Restart and load cache or exit.");
alertDialog.setIcon(R.drawable.tick);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton( "Restart", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
Toast.makeText(getApplicationContext(), "You chose to restart and load cache.", Toast.LENGTH_SHORT).show();
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity(i);
}
});
alertDialog.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help. ROE", Toast.LENGTH_SHORT).show();
wv.stopLoading();
wv.loadUrl( helpurl );
}
});
alertDialog.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose to exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.create();
alertDialog.show();
}
private class wvc extends WebViewClient
{
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
progress.setVisibility(View.VISIBLE);
if (url.contains(mycaturl))
{
WebSettings ws = wv.getSettings();
if ( !reachable(getApplicationContext()) )
{
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
roe();
}
else if ( ws.getCacheMode() == WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(), "loading cache coz not reachable", Toast.LENGTH_SHORT).show();
}
}
else
{
if ( ws.getCacheMode() == WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(), "Connection to server established.", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
Toast.makeText(getApplicationContext(), "PAGE DONE LOADING!!", Toast.LENGTH_SHORT).show();
//circular progress bar close
progress.setVisibility(View.GONE);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
super.onReceivedError(view, errorCode, description, failingUrl);
wv.stopLoading();
WebSettings ws = wv.getSettings();
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
wv.loadUrl(helpurl);
Toast.makeText(getApplicationContext(), "Page unavailable", Toast.LENGTH_SHORT).show();
}
else
{
wv.loadUrl(helpurl);
Toast.makeText(getApplicationContext(), "Page not cached", Toast.LENGTH_SHORT).show();
}
roe();
}
}
//checking connectivity by checking if site is reachable
public static boolean reachable(Context context)
{
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
try
{
URL url = new URL(mycaturl);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(5000); // five seconds timeout in milliseconds
urlc.connect();
if (urlc.getResponseCode() == 200) // good response
{ return true; } else { return false; }
}
catch (IOException e)
{ return false; }
}
else
{ return false; }
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onBackPressed ()
{
if (wv.isFocused() && wv.canGoBack())
{ wv.goBack(); } else { finish(); }
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.item1:
wv.loadUrl( helpurl );
break;
case R.id.item2:
wv.loadUrl( fbackurl );
break;
case R.id.item3:
String currurl=wv.getUrl();
wv.loadUrl(currurl);
break;
case R.id.item4:
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
break;
case R.id.item5:
finish();
break;
default:
break;
}
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState )
{
super.onSaveInstanceState(outState);
wv.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
wv.restoreState(savedInstanceState);
}
}
Should i include manifest? Thanks in advance.
let's say you want to handle caturl
then, in
if (url.contains(caturl){
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(mycaturl));
startActivity(i);
}
I want to implement google analytics sdk android v2
I had
Update AndroidManifest.xml
Create your analytics.xml file
But i don't know hot to implement EasyTracker methods
https://developers.google.com/analytics/devguides/collection/android/v2/#tracking-methods
I don't know where to put it in my code?
Sorry for my english...
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.MailTo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity
{
private static final String MIME_TYPE_EMAIL = null;
final Activity activity = this;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setPluginsEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
String scandinavianCharacters = null;
webView.loadDataWithBaseURL(null, scandinavianCharacters, "text/html", "UTF-8", null);
webView.getSettings().setUserAgentString("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Učitavanje...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
try {
webView.stopLoading();
} catch (Exception e) {
}
try {
webView.clearView();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("file:///android_asset/greska/greska.html");
super.onReceivedError(webView, errorCode, description, failingUrl);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://mobile.mywebsite.com/test/");
}
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.loadUrl(url);
return true;
}
WebView webView;
#Override
public void onBackPressed (){
if (webView.isFocused() && webView.canGoBack()) {
webView.goBack();
}
else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Zatvorite aplikaciju?")
.setMessage("Da li ste sigurni da želite da izađete?")
.setPositiveButton("Da", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}
})
.setNegativeButton("Ne", null)
.show();
}
}
public boolean shouldOverrideUrlLoading(webView view, String url) {
if(url.startsWith("mailto:")){
MailTo mt = MailTo.parse(url);
Intent i = IntentSupport.newEmailIntent(MainActivity.this, mt.getTo(), mt.getSubject(), mt.getBody(), mt.getCc());
startActivity(i);
view.reload();
return true;
}
else{
view.loadUrl(url);
}
return true;
}
;
public static Intent newEmailIntent(Context context, String address, String subject, String body, String cc) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { address });
intent.putExtra(Intent.EXTRA_TEXT, body);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_CC, cc);
intent.setType(MIME_TYPE_EMAIL);
return intent;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the currently selected menu XML resource.
android.view.MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
/** Called when a menu item in the menu is clicked. */
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuabout:
Toast.makeText(this, " " +
" " +
"", Toast.LENGTH_LONG).show();
return true;
// Generic catch all for all the other menu resources
default:
if (!item.hasSubMenu())
return true;
break;
}
return false;
}
}
You need to add two additional functions to your activity. You can add them at the bottom of your class at the very end:
#Override
public void onStart() {
super.onStart();
EasyTracker.getInstance().activityStart(this);
}
#Override
public void onStop() {
super.onStop();
EasyTracker.getInstance().activityStop(this);
}
The onStart() function is called after onCreate() so it will not affect the existing implementation. onStop() is called when the activity is stopped so it will catch things like your onBackPressed() action to stop the activity.
You can then choose to add additional tracking anywhere in your Activity using the send() functions such as the following:
EasyTracker.getTracker().sendEvent("Group", "Name", obj, value);
Unrelated by important - you should not be called System.exit(0) in your onBackPressed() function. If this is the only activity in your application, calling finish() will be enough to exit the application.
My give URL doesn't load with this code, however if I press 'home' key and click on app icon again(ie. resuming my activity) then it loads. I tried looking into activity lifecycle, tinkered with code but still it doesn't work. Please let me know if I need to clarify my question further. Thanks.
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.http.SslError;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView.SavedState;
import android.widget.Toast;
import com.ABC.R;
import com.ABC.util.CustomProgressDialogs;
import com.ABC.util.DeviceCheck;
import com.ABC.util.GlobalFunction;
import com.ABC.util.HTML5WebView;
import com.ABC.util.KeyBoard;
import com.ABC.util.NetworkCheck;
public class CanvasActivity extends Activity {
private HTML5WebView mWebView;
private ProgressDialog webPageDialog;
private Context context;
private GlobalFunction globalFunc;
private KeyBoard keyBoard;
private BroadcastReceiver connectionReceiver;
String myUrl;
SharedPreferences prefs;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Log.d("killapp", "killapp");
globalFunc.killApplication(context);
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog exitDialog = builder.create();
exitDialog.show();
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = CanvasActivity.this;
mWebView = new HTML5WebView(context);
// setContentView(mWebView.getLayout());
final DeviceCheck deviceCheck = new DeviceCheck(context); // change
// mWebView = new HTML5WebView(this);
// getWindow().requestFeature(Window.);
// setContentView()
// getWindow().
setContentView(mWebView.getLayout());
globalFunc = new GlobalFunction();
webPageDialog = new ProgressDialog(context);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Log.d("onReceivedError", failingUrl + " " + errorCode);
mWebView.loadUrl("file:///android_asset/myerrorpage.html");
}
#Override
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
super.onReceivedSslError(view, handler, error);
Log.d("onReceivedSslError", "ssl error");
handler.proceed();
// To supercede SSL certificate error.
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.d("page started", "page loading started");
webPageDialog.show();
webPageDialog.setContentView(CustomProgressDialogs
.iphoneProgressDialog(context));
webPageDialog.setCancelable(true);
// change
webPageDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
webPageDialog.dismiss();
globalFunc.killApplication(context);
}
});
}
#Override
public void onPageFinished(final WebView view, final String url) {
Log.i("onPageFinished", "onPageFinished");
if (webPageDialog.isShowing()) {
webPageDialog.dismiss();
}
}
});
if (getIntent().getStringExtra("Message") != null) {
Toast.makeText(getApplicationContext(),
getIntent().getIntExtra("push details", 0) + "",
Toast.LENGTH_LONG).show();
}
keyBoard = new KeyBoard(mWebView, context);
mWebView.addJavascriptInterface(keyBoard, "KeyBoard");
prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
/*
* if(prefs.getString("url",
* getResources().getString(R.string.MYURL_URL)).trim().equals("")){
* myUrl=getResources().getString(R.string.MYURL_URL).trim(); }else{
* myUrl = prefs.getString("url",
* getResources().getString(R.string.MYURL_URL)).trim(); }
* mWebView.loadUrl(myUrl);
*/
myUrl = getResources().getString(R.string.MYURL_URL).trim();
/*
* if (!myUrl.equalsIgnoreCase(prefs.getString("url",
* getResources().getString(R.string.MYURL_URL)).trim())) {
*
* myUrl = prefs.getString("url",
* getResources().getString(R.string.MYURL_URL)).trim();
*
* }
*/
// mWebView.loadUrl(myUrl);
if (new NetworkCheck(context).isOnline()) {
// change
webPageDialog.show();
webPageDialog.setContentView(CustomProgressDialogs
.iphoneProgressDialog(context));
webPageDialog.setCancelable(true);
webPageDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
webPageDialog.dismiss();
globalFunc.killApplication(context);
}
});
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
} else {
mWebView.loadUrl(myUrl);
/*
* if (deviceCheck.isTablet()) {
* setRequestedOrientation(ActivityInfo
* .SCREEN_ORIENTATION_LANDSCAPE); mWebView.loadUrl(myUrl); }
* else {
* setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
* ); mWebView.loadUrl(myUrl); }
*/
}
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
mWebView.loadUrl(myUrl);
}
#Override
public void onResume() {
super.onResume();
if (!((prefs.getString("url",
getResources().getString(R.string.MYURL_URL)).trim()))
.equals("")) {
myUrl = prefs.getString("url",
getResources().getString(R.string.MYURL_URL)).trim();
}
if (!(myUrl.equals(mWebView.getUrl()))) {
// mWebView.loadUrl(myUrl);
}
/*
* if (!mWebView.getUrl().equalsIgnoreCase(prefs.getString("url",
* getResources().getString(R.string.MYURL_URL)).trim())) {
*
* myUrl = prefs.getString("url",
* getResources().getString(R.string.MYURL_URL)).trim();
* mWebView.loadUrl(myUrl); }
*/
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("CanvasActivity-onOptionsItemSelected", "in option selected");
switch (item.getItemId()) {
case R.id.url:
startActivity(new Intent(this, EditURL.class));
return true;
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
Log.d("CanvasActivity-onCreateOptionsMenu",
"in oncreate option menu");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menuxml, menu);
return true;
}
#Override
public void onStop() {
super.onStop();
mWebView.stopLoading();
}
// onkeydown was here.
public void startBroadcastService() {
connectionReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
ConnectivityManager connManager1 = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mMobile = connManager1
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isNoNetwork = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (!isNoNetwork) {
if (mWifi.isAvailable()) {
}
if ((mWifi.isConnected() && mWifi.isAvailable())
|| (mMobile.isConnected() && mMobile.isAvailable())) {
if (mWebView.getUrl().contains("myerrorpage")) {
mWebView.loadUrl(myUrl);
}
}
}
}
};
registerReceiver(connectionReceiver, new IntentFilter(
"android.net.conn.CONNECTIVITY_CHANGE"));
}
}
I created a handler and loaded my URL after my webview is registered in that handler with relevent functions( onPageStarted onPageFinished and onReceivedError) , because my webview was taking much time to load the page. This worked.
handler = new Handler();
jsInterface = new JSInterface(mWebView, context, uniqueGeneratedkey,
handler);
handler.post(new Runnable() {
#Override
public void run() {
jsInterface.initiateProcess();
/*where initiateProcess() is the method where I register all the overridden
*functions ie. OnPageStarted() and OnPageFinished();
*/
}
});
mWebview.LoadUrl(url);