Android onBackPressed issue - android

I created a basic webview app following instructions from web.
everything works well except the backpress button, when webview connected to server backpress goes to home screen, but when i clicked the home in menu items (search and aboutpage) the app closed.
Here is my code
MainActivity.java
package com.dijitalyayincim.cekmekoy.cekmekoy_web;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
private WebView webView;
private boolean isRedirected;
private ProgressBar progress;
String url = "file:///android_asset/www/index.html";
String url1 ="http://www.cekmekoy.info/index.php?option=com_sppagebuilder&view=page&id=12";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(R.layout.aa);
webView = (WebView) findViewById(R.id.webView);
startWebView(webView, url);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_info:
Element adsElement = new Element();
adsElement.setTitle("Advertise with us");
View aboutPage = new AboutPage(this)
.isRTL(false)
.setImage(R.drawable.logo_cekmekoy)
.addItem(new Element().setTitle("Version 1.0"))
.addItem(adsElement)
.addGroup("Bize Ulaşın")
.addEmail("info#cekmekoy.info")
.addWebsite("http://www.cekmekoy.info/")
.addFacebook("cekmekoyinfo")
.addTwitter("cekmekoyinfo")
.addYoutube("UCYt3Z595jctz5oUhg0SMLqQ")
.addInstagram("cekmekoy_info")
.create();
setContentView(aboutPage);
setTitle("Bize Ulaşın");
return true;
case R.id.action_search:
setContentView(R.layout.test);
webView = (WebView) findViewById(R.id.search);
startWebView(webView, url1);
setTitle("Arama");
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
private void startWebView(WebView webView,String url) {
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
view.reload();
return true;
}
view.loadUrl(url);
isRedirected = true;
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
isRedirected = false;
}
public void onLoadResource (WebView view, String url) {
if (!isRedirected) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Yükleniyor...");
progressDialog.show();
}
}
}
public void onPageFinished(WebView view, String url) {
MainActivity.this.setTitle(view.getTitle());
try{
isRedirected=true;
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
#Override
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
i really appreciate if you can help
thanks...

#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Use this code. Hope help you.

Comment this finish line.and use your method. webView.goBack();
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// finish();
return true;
}
}

Related

How do I make my webview in android responsive to jquery and other js library

Hello stackoverflowers,
I created an android webView app for one of my partner website.
The website is mobile responsive.
Now we decided to develop an app webview android version for the website and we noticed, some slight changes which will affect user experience which are:
1) The nav menu is sticky on the brower and mobile browser but on the android webview, it is not sticky.
2) The popUp tour dialog is not positioning correctly on the webView.
I will attach screenshots
I will appreciate if I can get helps, hints on how to solve it. We tried to create the app on web2app platform and it works just fine.
web2App demo version
Android webView not responsive
The website link is tweecampus.com
package com.gaspercloud.tweecampus;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.res.ResourcesCompat;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
public class WebViewActivity extends AppCompatActivity {
private WebView webView;
private Context context;
private ProgressBar progressBar;
private float m_downX;
// private PullToRefreshView mPullToRefreshView;
private int REFRESH_DELAY = 3000;
private ImageView logo;
private String DEFAULT_ERROR_PAGE_PATH = "file:///android_asset/html/default_error_page.html";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
context = this;
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setLogo(R.drawable.t_icon_white60x60);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
progressBar = findViewById(R.id.progressBar);
webView = findViewById(R.id.webView);
initWebView();
webView.loadUrl(https://tweecampus.com);
/*
mPullToRefreshView = findViewById(R.id.pull_to_refresh);
mPullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
#Override
public void onRefresh() {
mPullToRefreshView.postDelayed(new Runnable() {
#Override
public void run() {
webView.loadUrl(webView.getUrl());
mPullToRefreshView.setRefreshing(false);
}
}, REFRESH_DELAY);
}
});*/
}
private void initWebView() {
webView.setWebChromeClient(new MyWebChromeClient(context));
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
logo.setVisibility(View.VISIBLE);
invalidateOptionsMenu();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
webView.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
logo.setVisibility(View.GONE);
invalidateOptionsMenu();
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
view.stopLoading();
try {
view.clearView();
} catch (Exception e) {
}
view.loadUrl("about:blank");
progressBar.setVisibility(View.GONE);
logo.setVisibility(View.GONE);
invalidateOptionsMenu();
webView.loadUrl(DEFAULT_ERROR_PAGE_PATH);
webView.clearHistory();
}
});
webView.clearCache(true);
webView.clearHistory();
webView.requestFocus();
webView.getSettings().setLoadsImagesAutomatically(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
//webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.getSettings().setSavePassword(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
//this is to reload webPage via JavaScript
webView.addJavascriptInterface(new SimpleWebJavascriptInterface(this, webView), "Android");
webView.setHorizontalScrollBarEnabled(false);
webView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getPointerCount() > 1) {
//Multi touch detected
return true;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
// save the x
m_downX = event.getX();
}
break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP: {
// set x so that it doesn't move
event.setLocation(m_downX, event.getY());
}
break;
}
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.browsermenu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (!webView.canGoBack()) {
menu.getItem(0).setEnabled(false);
menu.getItem(0).getIcon().setAlpha(130);
} else {
menu.getItem(0).setEnabled(true);
menu.getItem(0).getIcon().setAlpha(255);
}
if (!webView.canGoForward()) {
menu.getItem(1).setEnabled(false);
menu.getItem(1).getIcon().setAlpha(130);
} else {
menu.getItem(1).setEnabled(true);
menu.getItem(1).getIcon().setAlpha(255);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
if (item.getItemId() == android.R.id.home) {
finish();
}
if (item.getItemId() == R.id.action_back) {
back();
}
if (item.getItemId() == R.id.action_forward) {
forward();
}
return super.onOptionsItemSelected(item);
}
private void back() {
if (webView.canGoBack()) {
webView.goBack();
}
}
private void forward() {
if (webView.canGoForward()) {
webView.goForward();
}
}
private class MyWebChromeClient extends WebChromeClient {
Context context;
public MyWebChromeClient(Context context) {
super();
this.context = context;
}
}
#Override
protected void onResume() {
super.onResume();
if (webView.canGoBack()) {
webView.goBack();
} else if (webView.canGoForward()) {
webView.reload();
} else {
webView.loadUrl(getString(R.string.tweecampuswebsite));
}
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}

I am getting this error on pressing volume button

I have created a webview app. On pressing volume keys, my app crashes. This is the error in logcat
W/ViewRootImpl[MainActivity]: Cancelling event due to no window focus:
KeyEvent { action=ACTION_UP, keyCode=KEYCODE_VOLUME_DOWN,
scanCode=114, metaState=0, flags=0x28, repeatCount=0,
eventTime=196583031, downTime=196582864, deviceId=9, source=0x101 }
Below is my MainActivity.java file:
package app.freeairdrop.io;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends Activity{
private ProgressBar progressBar;
private WebView webView;
private SwipeRefreshLayout mySwipeRefreshLayout;
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClientDemo());
webView.setWebChromeClient(new WebChromeClientDemo());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
webView.loadUrl("http://freeairdrop.io/");
mySwipeRefreshLayout = (SwipeRefreshLayout)this.findViewById(R.id.swipeContainer);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
mySwipeRefreshLayout.setRefreshing(false);
}
}
);
}
private class WebViewClientDemo extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
if (uri.getHost() != null && (url.startsWith("https://freeairdrop.io/") || url.startsWith("https://www.freeairdrop.io/"))) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
progressBar.setProgress(100);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
}
private class WebChromeClientDemo extends WebChromeClient {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
else {
finish();
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#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();
}
}
}
Remove
finish();
from here :
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
else {
finish();
}
add focus to webview using:
<WebView android:id="#+id/webview"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusable="true"/>
Or
webview.requestFocus(View.FOCUS_DOWN|View.FOCUS_UP);
Remove call to finish() from here,
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
else {
finish(); // Remove this, onBackPressed() should handle it.
}
return super.onKeyDown(keyCode, event);
}

android webview: website controls not working

I have created android webview application.
But links or buttons on the webpage doesnt work.
I can saythat it doesnt load properly.
You can find the MainActivity.java here
package com.tunghuynh.comparotel;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.res.Configuration;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
private WebView webView;
private ProgressBar progress;
private RelativeLayout splash;
//private RelativeLayout imgSplash;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
splash = (RelativeLayout) findViewById(R.id.webview);
//imgSplash = (RelativeLayout) findViewById(R.id.imgSplash);
splash.setVisibility(View.INVISIBLE);
webView = new WebView(this);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
MainActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
try {
if (newProgress >= 100) {
splash.setVisibility(View.VISIBLE);
splash.addView(webView);
progress.setVisibility(View.INVISIBLE);
}
} catch (Exception e) {
}
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
String url = Global.urlComparotel;
switch (Global.type) {
case 0:
url = Global.urlComparotel;
break;
case 1:
url = Global.urlHotelcito;
break;
case 2:
url = Global.urlHotelinha;
break;
case 3:
url = Global.urlHotelomat;
break;
case 4:
url = Global.urlOtelcik;
break;
default:
url = Global.urlComparotel;
}
openWeb(url);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.activity_main);
}
private void openWeb(String url) {
webView.loadUrl(url);
MainActivity.this.progress.setProgress(0);
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;// super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.item1:
webView.reload();
break;
case R.id.item2:
shareTextUrl();
break;
case R.id.item3:
Intent int1 = new Intent(MainActivity.this, AboutUs.class);
startActivity(int1);
break;
case R.id.item4:
rateApp();
break;
case R.id.item5:
finish();
break;
}
//shareTextUrl();
return false;// super.onOptionsItemSelected(item);
}
private void rateApp() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=" + this.getPackageName()));
if (!MyStartActivity(intent)) {
intent.setData(Uri
.parse("https://play.google.com/store/apps/details?id="
+ this.getPackageName()));
if (!MyStartActivity(intent)) {
Toast.makeText(
this,
"Could not open Android market, please install the market app.",
Toast.LENGTH_SHORT).show();
}
}
}
private boolean MyStartActivity(Intent aIntent) {
try {
startActivity(aIntent);
return true;
} catch (ActivityNotFoundException e) {
return false;
}
}
private void shareTextUrl() {
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("text/plain");
share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
share.putExtra(Intent.EXTRA_TEXT,
"https://play.google.com/store/apps/details?id=" + this.getPackageName());
startActivity(Intent.createChooser(share, "Share application!"));
}
}
http://www.a2b4.net/MainActivity.java
How we can resolve the problem.
Since your website needs javascript you should enable javascript execution in your webview:
webview.getSettings().setJavaScriptEnabled(true);
see also documentation
Update: You can suppress the warning message Warning: Using setJavaScriptEnabled can introduce XSS vulnerabilities into you application by adding:
#SuppressLint("SetJavaScriptEnabled") // add this
#Override
protected void onCreate(Bundle savedInstanceState) {
above the onCreate method.

Adding loading spinner on Action Bar while the WebView loads?

I am developing an android app. which is using webview to render a html page but it stays blank while the page loads. I want to add a loading spinner in the action bar so the user knows that something is loading and it not blank.
Please can anyone guide me how to do that.
My existing code -
package com.pranavsethi.dpsrkp;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.DownloadListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Achievements extends Activity{
private WebView mWebView;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webvew_client_layout);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
//For web view
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true); //enable javascript
mWebView.getSettings().setBuiltInZoomControls(true); //enable zoom
mWebView.getSettings().setDisplayZoomControls(false);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
mWebView.setScrollbarFadingEnabled(true);
mWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
// handle download, here we use brower to download, also you can try other approach.
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
mWebView.loadUrl("http://pranavsethi.tk"); // name of website to load
mWebView.setWebViewClient(new HelloWebViewClient()); //removing loading progressbar
}
private class HelloWebViewClient extends WebViewClient{ //our web client
#Override
public void onReceivedError(WebView view, int errorCode, //Code for checking the internet connection and return the error if fails
String description, String failingUrl) {
Intent intent = new Intent(Achievements.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return;
}
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int KeyCode, KeyEvent event)
{
if ((KeyCode)== KeyEvent.KEYCODE_BACK && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(KeyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
overridePendingTransition (R.anim.right_slide_in, R.anim.fade_out);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
public void onBackPressed()
{
this.finish();
overridePendingTransition (0, R.anim.right_slide_out);
return;
}
}
SOLUTION
Add the following -
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setProgressBarIndeterminateVisibility(true);
After -
super.onCreate(savedInstanceState);
And this in your WebViewClient
private class HelloWebViewClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url){
webview.loadUrl(url);
setProgressBarIndeterminateVisibility(true);
return true;
}
#Override
public void onPageFinished(WebView webview, String url){
super.onPageFinished(webview, url);
setProgressBarIndeterminateVisibility(false);
}
}

How to implement google analytics sdk android v2

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.

Categories

Resources