Creating An In-Game Web Browser on Android - java

In my game, I'd like to have a kind of "message of the day" feature. Basically, when the user taps the "message of the day" button in the main menu, it would open up a browser view in-game. When the user is done, he taps a "close" button and the view disappears, returning him to the game menu.
So, is it possible to create a browser view dynamically? If yes, how?

The following can be used in a Dialog as well
public void setWebView() {
//WebViewClient is used if you want to capture stuff from the webview, like if a link was pressed
WebViewClient yourWebClient = new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
open_web = true;
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "http://" + url;
}
Intent browserIntent = new Intent("android.intent.action.VIEW",
Uri.parse(url));
startActivity(browserIntent);
return true;
}
};
WebView wv = (WebView) findViewById(R.id.webview);
wv.setWebViewClient(yourWebClient);
String str = getHtml();
wv.loadData(str, "text/html", "utf-8");
wv.setBackgroundColor(0);
}
boolean isAsset = false;
private String getHtml(){
InputStream source = null;
if (isAsset){
source = getAssets().open("motd.html");
} else {
source = new FileInputStream(Environment.getExternalStorageDirectory() + "motd.html");
}
}

You could probably just use a WebView. When you want it to show up you could just set its view state to View.VISIBLE. When you want it to go away, just set its view state to View.GONE.

You can add/remove a WebView to your game dynamically (or show/hide it, whatever you prefer).
Take a look at the WebView tutorial for more info:
http://developer.android.com/resources/tutorials/views/hello-webview.html
Make sure to leave room for your "Close" button in your layout, i.e. you don't want to set the layout height to "fill_parent".

Related

programmatically click on a HTML button in WebView from fragment in Android

I need to open a dialog in a website which opens on clicking a HTML button of the website. I'm trying to click on a HTML button based on the id from the fragment, how can I perform the action, I'm using
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// trying to click the button with id btn-to-be-clicked
webView.loadUrl("javascript:(function(){document.getElementById('btn-to-be-clicked').click();})()");
}
}
thanks
I tried
webView.loadUrl("javascript:(function(){document.getElementById('btn-to-be-clicked').click();})()");
so apparently you must specify every line in a new string
extracted the js to a variable with multi line, it has to be a multi line concatenated string
val jsFunction = "javascript:(function() { " +
"document.getElementById('btn-to-be-clicked').click();" +
"})()"

How to open html string "a href" to Webview?

how can i open the html string that has a href on webview only instead of going on your browser?
i am using the LinkMovementMethod, this is okay on opening it on other app like video from youtube but i have some links that needs to be open only on webview.
here is a sample html string
String html_text = "<h1>sample text</h1><p><small>February 1 1970</small></p><p class=\"text-center\"><img src=\"https://www.google.com\" /></p><p>sample (here).</p>"
i need the a href to be open only on webview.
here is my code
DetailActivity
public class DetailActivity extends AppCompatActivity implements Html.ImageGetter {
private TextView newsContentTv;
private WebView newsWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_news);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
newsWebView = (WebView) findViewById(R.id.newsWebView);
setSupportActionBar(toolbar);
// add back arrow to toolbar
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
newsContentTv = (TextView) findViewById(R.id.textNewsContext);
Intent i = getIntent();
String news_content = i.getStringExtra("detail_content");
Spanned spanned = Html.fromHtml(news_content, this, null);
Spannable spannable = new SpannableString( Html.fromHtml(news_content) );
newsContentTv.setText(spanned);
newsContentTv.setMovementMethod(LinkMovementMethod.getInstance());
}
any help would be really appreciated.
// Create an unencoded HTML string
// then convert the unencoded HTML string into bytes, encode
// it with Base64, and load the data.
String html_text =
"<h1>sample text</h1><p><small>February 1 1970</small></p><p class=\"text-center\"><img src=\"https://www.google.com\" /></p><p>sample (here).</p>";
String encodedHtml = Base64.encodeToString(html_text.getBytes(),
Base64.NO_PADDING);
newsWebView.loadData(encodedHtml, "text/html", "base64");
I hope this will help you.
WebView webview = (WebView)this.findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadDataWithBaseURL("", data, "text/html", "UTF-8", "");
Your question states you need to open the clicked url in your webview instead of navigating to browser. I can think of two ways to do this.
First case, if its not necessary to have a Textview to display the clickable link then you can load your string into the WebView itself (as others mentioned) and set a WebViewClient (this part is important)
newsWebView.loadDataWithBaseURL(null, html_text, "text/html", "UTF-8", null);
newsWebView.setWebViewClient(new WebViewClient());
// add below line to support youtube videos etc.
newsWebView.getSettings().setJavaScriptEnabled(true);
newsWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
so that any click keeps the navigation in the same WebView. Without the client it will navigate to the browser. But you should note this will load and replace the content inside, so your original link will not be there on screen.
Second case, if you need the clicks to be from the TextView simply setting newsContentTv.setMovementMethod(LinkMovementMethod.getInstance()); won't work as by default it will make the normal intent causing it to navigate to browser or related apps, you need to remove that. Then, you have to create a custom class extending LinkMovementMethod and override the touch event to load the url clicked into your webview as shown below:
public class CustomLinkMovementMethod extends LinkMovementMethod {
private static CustomLinkMovementMethod instance;
public static CustomLinkMovementMethod getInstance() {
if (instance == null)
instance = new CustomLinkMovementMethod();
return instance;
}
#Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_UP) {
int x = (int) event.getX() - widget.getTotalPaddingLeft() + widget.getScrollX();
int y = (int) event.getY() - widget.getTotalPaddingTop() + widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
URLSpan[] urlSpans = buffer.getSpans(off, off, URLSpan.class);
if (urlSpans.length != 0) {
// You can check log to see if you are getting the url on click.
Log.d("TAG", String.valueOf(urlSpans[0].getURL()));
/* If you've made this an inner class in your activity
you can directly load the url into your webview.
Else you will have to create listeners to get url in activity
on event trigger */
newsWebView.loadData(urlSpans[0].getURL());
return true;
}
}
return super.onTouchEvent(widget, buffer, event);
}
}
use this on the TextView like
newsContentTv.setMovementMethod(CustomLinkMovementMethod.getInstance());
See if this works for you, hadn't expected the answer to become this long.

WebView - only show back button if back history exists

I developed a simple webview app. I added a button which should act as the back button, so users can navigate back one page.
The button is initially hidden and should only show if a back history exists.
How can I realise this?
The code is simple:
backButton = findViewById(R.id.backButton);
backButton.setEnabled(blizzView.canGoBack());
but where do I have to call this? How is the "some site loaded" event called?
Update:
I tried to apply #Murats answer, but nothing happens:
private WebView blizzView; // my webview
private Button backButton;
public void onPageFinished(WebView view, String url)
{
backButton = findViewById(R.id.backButton);
backButton.setEnabled(blizzView.canGoBack());
if (blizzView.canGoBack()) {
backButton.setVisibility(View.VISIBLE);
} else {
backButton.setVisibility(View.INVISIBLE);
}
}
You can use WebView#canGoBack to find out if there is a backstack. You can check for that after the page is loaded e.g. in WebViewClient#onPageFinished
It works like this:
blizzView.setWebViewClient(new WebViewClient() { //
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
backButton = findViewById(R.id.backButton);
backButton.setEnabled(blizzView.canGoBack());
if (blizzView.canGoBack()) {
backButton.setVisibility(View.VISIBLE);
} else {
backButton.setVisibility(View.INVISIBLE);
}
}
});

How can I open multiple PDF Links in Android WebView in Android?

I'm building android app where, I placed links to the page in webview on which multiple links are there pointing to PDFs. Everyday, new links are updated. I want to make such functionality that when user clicks on the particular PDF link, it should get opened in default PDF viewer or there itself.
Right now, nothing is happening when user clicks on PDF link within webview.
WebView w=(WebView)findViewById(R.id.web1);
WebSettings webSettings=w.getSettings();
webSettings.setDomStorageEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
w.setWebViewClient(new WebViewClient());
w.loadUrl("http://collegecirculars.unipune.ac.in/sites/examdocs/_layouts/mobile/view.aspx?List=7ed6607e-6c43-401a-a922-bf8d8bf08ed8&View=dc261157-c533-4a60-977b-506fd87b2a19");
You can use Google Docs Viewer to read your pdf online:
WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
String pdf = "http://collegecirculars.unipune.ac.in/sites/examdocs/Examiantions%20Timetables/Master-In-ARTS(M.A)(Rev.2008)-(24908)_Spl4-8-16.pdf?Mobile=1&Source=%2Fsites%2Fexamdocs%2F_layouts%2Fmobile%2Fview%2Easpx%3FList%3D7ed6607e%252D6c43%252D401a%252Da922%252Dbf8d8bf08ed8%26View%3Ddc261157%252Dc533%252D4a60%252D977b%252D506fd87b2a19%26ViewMode%3DSimple%26CurrentPage%3D1";
webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);
open in browser
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(pdf_url));
startActivity(browserIntent);
To override current URL :
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
// here you can check PDF
url = url.toLowerCase();
view.loadUrl(url);
return true;
}
}
set this MyWebViewClient to your webView.
PaymentWebViewClient paymentWebViewClient = new PaymentWebViewClient();
webView.setWebViewClient(paymentWebViewClient);

Launching a open a browser when clicking a link in android webview

I'm trying to make a link inside my android webview load into one of the web browsers available onto the device. What is happening is that it just loads the link inside the webview. How can I make the link load outside the webview of my application?
The link that I am need to make work is this:
Forgot your password?
When I click it nothing happens, I need it to call the default web browser of the device.
My shouldOverrideUrlLoading is currently being used to check the URL and loads another activity if it is equal:
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("extraData", "the urls"+Uri.parse(url).getPath());
if (Uri.parse(url).getPath().equals("/qr_code")) {
progress.setVisibility(View.GONE);
Intent intent = new Intent(getApplicationContext(),QRActivity.class);
startActivityForResult(intent, 1);
setContentView(R.layout.activity_qr);
//return true;
}
if(Uri.parse(url).getPath().equals("/linka")){
return true;
}
return false;
}
Update: It is now working but for some reason my current webView still runs the link therefore the pages loads to the link clicked
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("extraData", "the urls"+Uri.parse(url).getPath());
if (Uri.parse(url).getPath().equals("/TMMobile/Main/qr_code")) {
//return true;
}
if(Uri.parse(url).getPath().equals("/linka")){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://testdomain/RecoverPassword.aspx"));
startActivity(browserIntent);
}
return false;
}
}
To open a URL in a browser, just can use the following code:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);

Categories