I have created an application that uses WebView to view my website, the application is running smoothly and without any bugs, I even uploaded it on the Google Play store. The only thing is that I have youtube video links in my website and they don't work on my application. They appear on the screen and the user can easily click on them, but after clicking the video loading sign appear and stays rotating without any benefit. I know that mobile web browser have no flash player plug-in and I have looked at all the similar questions on StakcOverFlow. So what I would like to do is to make my application call the YouTube app from the android system and let it complete the mission by playing my website youtube videos. I read about Intent methode, but couldn't find anything helpful. Any Suggestions guys?
Thank you svenoaks. Now I have a small error in the code:
package com.parse;
import android.net.Uri;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class ParserActivity extends Activity {
private WebView myWebView;
#SuppressLint({"setJavaScriptEnabled"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parser);
myWebView =(WebView) findViewById(R.id.webview);
myWebView.loadUrl("https://parse.com/apps/aramco-app1/push_notifications /new");
myWebView.setWebViewClient(new HelloWebViewClient());
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setLoadWithOverviewMode(true);
myWebView.getSettings().setUseWideViewPort(true);
myWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
myWebView.setScrollbarFadingEnabled(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setSupportZoom(true);
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{webview.loadUrl (url);
return true;
{
// YouTube video link
if (url.startsWith("vnd.youtube:"))
{
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse
(String.format("http://www.youtube.com/v/%s", url.substring("vnd.youtube:".length())))));
return true;
}
return false;
}
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
Toast.makeText(WebActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack())
{
myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
public boolean setIsZoomInEnabled;
}
class WebAppInterface {
Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
private void show()
{
// TODO: Implement this method
}
}
onReceive method has an Error.
This worked for me pre KitKat, but now I can't even see the videos in the webview to click on, because of no plug-in. Hopefully it will work for you:
webView.setWebViewClient(new 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
(String.format("http://www.youtube.com/v/%s", url.substring("vnd.youtube:".length())))));
return true;
}
return false;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
Toast.makeText(WebActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
Related
I have a working Android webview App I made using Android Studio, I needed to make it open links that contains "_blank" externally.
I added the code below
#Override
public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, android.os.Message resultMsg)
{
WebView.HitTestResult result = view.getHitTestResult();
String data = result.getExtra();
Context context = view.getContext();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(data));
context.startActivity(browserIntent);
return false;
}
But the first line of the code "#Override" shows the error below
> Task :app:compileDebugJavaWithJavac FAILED
...\MainActivity.java:58: error: method does not override or implement a method from a supertype
#Override
^
Note: ...\MainActivity.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error
Below is the Full "MainActivity" Code
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements Main_Activity, Main__Activity {
WebView webView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.web);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(false);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setSupportMultipleWindows(true);
webView.getSettings().setUseWideViewPort(false);
webView.setWebViewClient(new WebViewClient() {
});
webView.loadUrl("file:///android_asset/app.html");
}
public class myWebViewClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("file:///android_asset/error.html");
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
super.onReceivedSslError(view, handler, error);
handler.cancel();
}
#Override
public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, android.os.Message resultMsg)
{
WebView.HitTestResult result = view.getHitTestResult();
String data = result.getExtra();
Context context = view.getContext();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(data));
context.startActivity(browserIntent);
return false;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
I've tried several locations for the code but the error persists. I want to get the error off and achieve the reason why I added the code; to open target"_blank" outside the webview app.
Go to build gradle (project) or setting
insert this line before
repositories {
google()
maven Central()
} //
this Line before insert This -> image
and #synk project
#android_studio
The error tells you what is the problem. WebViewClient does not have any method called onCreateWindow.
WebChromeClient does.
public class MyChromeViewClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, android.os.Message resultMsg)
{
WebView.HitTestResult result = view.getHitTestResult();
String data = result.getExtra();
Context context = view.getContext();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(data));
context.startActivity(browserIntent);
return false;
}
}
WebView can have both of them so you just have to create your own version of the WebChromeClient and add it to it.
// Also BTW you are not using your implementation - it should be new myWebViewClient()
webView.setWebViewClient(new WebViewClient());
//webView.setWebViewClient(new myWebViewClient());
webView.setWebChromeClient(new MyChromeViewClient());
I developed a small android webview app to access an internal (local network) PHP based site.
Here is my code:
package com.CheckInventory;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
#SuppressWarnings("unused")
public class CheckInventoryActivity extends Activity {
WebView webview;
String username;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
WebView webView = (WebView) findViewById(R.id.webview);
webView.setBackgroundColor(0);
webView.setBackgroundResource(R.drawable.myimage);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
WebSettings webSettings = webview.getSettings();
webSettings.setLoadWithOverviewMode(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setDatabasePath("/data/data/"+this.getPackageName()+"/databases/");
webSettings.setDomStorageEnabled(true);
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("http://192.168.0.124/android");
webview.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown (int keyCode, KeyEvent event) {
if((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()){
//webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
The site has authentication, but I would like to add some authentication between the app and the site (How do I do this? pass a parameter maybe when the url is invoked), secondly and more importantly, where specifically do I put the onReceivedError so the user never sees the url or the page down if they walk away from the building or loose connection.
public void onReceivedError(WebView view, int errorCod,String description, String failingUrl) {
Toast.makeText(Webform.this, "Your Internet Connection May not be active Or " + description , Toast.LENGTH_LONG).show();
}
I saw this explanation in Detecting Webview Error and Show Message but I do not know where to implement it.
Thank you in advance
You need to create class which extends WebViewClient and implements method OnReceivedError
like this
class myWebClient extends WebViewClient {
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Toast.makeText(Webform.this, "Your Internet Connection May not be active Or " + description , Toast.LENGTH_LONG).show();
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
and then you need to set new WebViewClient to your WebView
web = (WebView) findViewById(R.id.webview);
web.setWebViewClient(new myWebClient());
Hope this helps
You can add onReceivedError in Your HelloWebViewClient class and handle what you want to handle when you get error.
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error){
//Your code to do
Toast.makeText(getActivity(), "Your Internet Connection May not be active Or " + error , Toast.LENGTH_LONG).show();
}
}
I'm trying to sort out a web app but cannot find a possible way to include the use of a back button via the phone's soft keys. How can I go about doing this?
i.e I want to use the back button on my phone to return to the previous viewed web page.
Thank you
Jordan
package com.wear2gym;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class Wear2gym extends Activity
{
final Activity activity = this;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Pumping some iron...");
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)
{
Toast.makeText(activity, "Sorry but there is no internet connection! " , Toast.LENGTH_LONG).show();
view.loadUrl("file:///android_asset/nointernet.html");
// Handle the error
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://wear2gym.co.uk");
webView.canGoBack();
}
}
I wouldn't recommand onBackPressed() as thatÅ› only available since API level 5
You will find great info here: http://developer.android.com/guide/webapps/webview.html
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack() {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
override the onBackPressed() method:
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
}
else {
super.onBackPressed();
}
}
This will go back on the WebView until it can't go back, in which case it will exit the Activity
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);
This is my code:
package com.testappmobile;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class testappmobileActivity extends Activity
{
final Activity activity = this;
private WebView webview;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the BACK key and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
// If it wasn't the BACK key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Loading...");
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)
{
// Handle the error
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://developer.android.com/index.html");
}
}
Now im having trouble getting the hardware back button to work. The app loads fine as does page and everything else but as soon as i hit the phones back button it crashes then forces close.
I've searched google for the last 3 hours and have only found vague answers with very little info or broken links. Google's instructions sucked also as i am a beginner and they presume you know a certain amount.
Where should I place the code if it is in the wrong place?
Are there errors?
Cheers!
You have created a webView reference at class level but never initialized it thats why NullPointerException. I've made a small change in the onCreate method in your code, analyze it and make the necessary change(s);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
// Don't create another webview reference here,
// just use the one you declared at class level.
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
// rest of code same
// ...
// ...
// ...
}
Hope you got it. :)
You have two different references to WebView. First local in onCreate, that is lost. Second webview member that you use in onKeyDown, but that is null all the time.