Webview - Open links in external browser? - android

Can anyone help me in opening specific link in External browser or other android app?
For Example if URL matches whatsapp:// then it should open link in WhatsApp app and if WhatsApp is not installed then it should open https://play.google.com/store/apps/details?id=com.whatsapp in android browser.
FYI: I am using https://github.com/SurfEdge/flarum-mobile-android to create Web View App for my Forum website.
My Android code looks like:
package com.example.example;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import im.delight.android.webview.AdvancedWebView;
public class MainActivity extends AppCompatActivity implements AdvancedWebView.Listener{
public AdvancedWebView webView;
private ProgressBar mPbar = null;
private static final String url = "https://example.com/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mPbar = (ProgressBar) findViewById(R.id.loader);
webView = (AdvancedWebView) findViewById(R.id.newWeb);
webView.loadUrl(url);
webView.setListener(this, this);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
webSettings.setAllowFileAccess(true);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
AdvancedWebView newWebView = new AdvancedWebView(MainActivity.this);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
webSettings.setAllowUniversalAccessFromFileURLs(true);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
mPbar.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url) {
mPbar.setVisibility(View.GONE);
}
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("whatsapp://")) {
final Uri uri = Uri.parse("market://details?id=com.whatsapp");
final Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
#SuppressWarnings({"NewApi", "deprecation"})
final int newDocumentFlag = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) ? Intent.FLAG_ACTIVITY_NEW_DOCUMENT : Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | newDocumentFlag | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException ex) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.whatsapp")));
}
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
});
webView.setOnKeyListener( new View.OnKeyListener() {
#Override
public boolean onKey( View v, int keyCode, KeyEvent event ) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return false;
}
});
webView.setThirdPartyCookiesEnabled(true);
webView.setCookiesEnabled(true);
}
#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) {
// 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
webView.onResume();
}
#Override
protected void onPause() {
webView.onPause();
super.onPause();
}
#Override
protected void onDestroy() {
webView.onDestroy();
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
webView.onActivityResult(requestCode, resultCode, intent);
}
#Override
public void onBackPressed() {
if (!webView.onBackPressed()) { return; }
super.onBackPressed();
}
#Override
public void onPageStarted(String url, Bitmap favicon) {
}
#Override
public void onPageFinished(String url) {
}
#Override
public void onPageError(int errorCode, String description, String failingUrl) {
}
#Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
}
#Override
public void onExternalPageRequest(String url) {
}
}
Error:
Error:(86, 11) error: cannot find symbol class Uri
Error:(86, 21) error: cannot find symbol variable Uri
Error:(94, 22) error: cannot find symbol class ActivityNotFoundException
Error:(95, 62) error: cannot find symbol variable Uri
P.S: I am not an Android Developer

You should override shouldOverrideUrlLoading, determine if the url has the specified prefix, and then open the Whatsapp listing on Play Store, or if the Play Store is not installed, open it inside browser :
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
mPbar.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url) {
mPbar.setVisibility(View.GONE);
}
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("whatsapp://")) {
// create an intent for Play Store
final Uri uri = Uri.parse("market://details?id=com.whatsapp");
final Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
#SuppressWarnings({"NewApi", "deprecation"})
final int newDocumentFlag = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) ? Intent.FLAG_ACTIVITY_NEW_DOCUMENT : Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | newDocumentFlag | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
// open Whatsapp listing in Play Store app
startActivity(goToMarket);
} catch (ActivityNotFoundException ex) {
// open Whatsapp listing in browser
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.whatsapp")));
}
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
});
EDIT
Add this lines to the top of the file to import the necessary classes :
import android.content.ActivityNotFoundException;
import android.net.Uri;

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();
}
}
}

webview android app not loading any image or navigate in the website link

I am trying to load the site in an android app web view.
The site loads without the images ,all the images from the site are not loaded and i can't add to the cart product or even open details of other product
The code for MainActivity.java is shown below.
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://shopliek.com");
mWebView.setWebViewClient(new MyAppWebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
}});
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/** Inflating the current activity's menu with res/menu/items.xml */
getMenuInflater().inflate(R.menu.menu_main, menu);
/** Getting the actionprovider associated with the menu item whose id is share */
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
/** Setting a share intent */
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return super.onCreateOptionsMenu(menu);
}
/** Returns a share intent */
private Intent getDefaultShareIntent(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Make your Life Easier");
intent.putExtra(Intent.EXTRA_TEXT," Visit google");
return intent;
}
}
and also this MyAppWebViewClient:
public class MyAppWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("www.shopliek.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
I'm beginner so please explain kindly with simple instruction and thanks
Try this
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.google.com");
Hope this will work. Let me know if it works.
I've used the below code & everything worked correctly: show pictures, details page ... ...
public class WebviewActivity extends Activity {
#BindView(R.id.webview)
WebView web;
#BindView(R.id.progressBar)
ProgressBar progressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
ButterKnife.bind(this);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(WebserviceUrl.BASE_URL);
} catch (Exception e) {
e.printStackTrace();
}
}
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) {
progressBar.setVisibility(View.VISIBLE);
web.loadUrl(url);
return true;
}
public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
final AlertDialog.Builder builder = new AlertDialog.Builder(WebviewActivity.this);
builder.setMessage(R.string.notification_error_ssl_cert_invalid);
builder.setPositiveButton(R.string.continue_to_page, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.proceed();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.cancel();
}
});
final AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
}
try it & let me know the result

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.

Android progressBar random crash with nullPointerException, can't understand why

Here's one of the tabs I have that loads a page.
package realstrat.cfostudio.magazineapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import realstrat.cfostudio.magazineapp.R;
public class TabActivity3 extends Activity {
WebView mWebView;
private ProgressDialog progressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.loadUrl("--company URL--");
mWebView.setWebViewClient(new FirstTabWebViewClient());
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean("OverviewMode", mWebView.getSettings().getLoadWithOverviewMode());
mWebView.saveState(savedInstanceState);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
((WebView)findViewById(R.id.webview1)).restoreState(savedInstanceState);
if (savedInstanceState.getBoolean("OverviewMode") == false) {
((WebView)findViewById(R.id.webpageview)).getSettings().setLoadWithOverviewMode(false);
((WebView)findViewById(R.id.webpageview)).getSettings().setUseWideViewPort(false);
}
else {
((WebView)findViewById(R.id.webpageview)).getSettings().setLoadWithOverviewMode(true);
((WebView)findViewById(R.id.webpageview)).getSettings().setUseWideViewPort(true);
}
return;
}
private class FirstTabWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// YouTube video link
if (url.startsWith("vnd.youtube"))
{
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return (true);
}
if (url.endsWith("-m.html")){
mWebView.getSettings().setLoadWithOverviewMode(false);
mWebView.getSettings().setUseWideViewPort(false);
}
else {
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
}
view.loadUrl(url);
return true;
}
public void onPageStarted(WebView view, String url, Bitmap favicon){
progressBar = ProgressDialog.show(TabActivity3.this, "", "Loading...", true);
}
public void onPageFinished(WebView view, String url) {
progressBar.hide();
if (url.endsWith("-m.html")){
mWebView.getSettings().setLoadWithOverviewMode(false);
mWebView.getSettings().setUseWideViewPort(false);
}
else {
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
}
return;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Context context = getApplicationContext();
CharSequence text = "Desc: " + description;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
return;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Once in a while it will crash with a nullPointerException on the line progressBar.hide() under onPageFinished(). That doesn't make any sense since onPageStarted() starts the progressBar, and onPageStarted always comes before onPageFinished(). Why is this?
This only happens like, once in 10 times or something, which is really confusing to me.
It usually happens (always?) when the activity is being started for the first time.
try this
if(progressBar!=null)
progressBar.hide();
Maybe the Activity has been restarted in between the two callbacks? Try rotating the phone while the progressBar is shown to see what the results are.
Try to load progress bar as singleton object. If you create anther progress bar object before hide first one then second progress bar will crash in hide().
if(_progressBar == null)
_progressBar = new ProgressDialog(this);

Categories

Resources