Android WebView not stopping after user presses back - android

I am playing a YouTube video inside a WebView. I am able to play it, but when the person leaves the screen, I am not able to stop the audio from playing.
I tried various things inside onDestroy and onPause, or taking them out entirely, but they didn't seem to make a difference.
Would anyone know why the audio keeps playing and doesn't stop even after the app is turned off and the user opens other apps?
Here is my code for the whole class:
import com.flurry.android.FlurryAgent;
import utils.SendEmail;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.PluginState;
import android.widget.Button;
public class YoutubeActivity extends Activity
{
WebView webview = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
webview = new WebView(this);
setContentView(webview);
webview.getSettings().setAppCacheEnabled(false);
webview.getSettings().setJavaScriptEnabled(true);
webview.setInitialScale(1);
webview.getSettings().setPluginState(PluginState.ON);
WebSettings webSettings = webview.getSettings();
webSettings.setLoadsImagesAutomatically(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setUseWideViewPort(true);
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
webview.setWebChromeClient(new WebChromeClient(){});
webSettings.setDomStorageEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setAppCachePath(getApplicationContext().getFilesDir().getAbsolutePath() + "/cache");
webSettings.setDatabaseEnabled(true);
webSettings.setDatabasePath(getApplicationContext().getFilesDir().getAbsolutePath() + "/databases");
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences( YoutubeActivity.this);
String url_to_watch = prefs.getString( "url_to_watch" , null );
webview.loadUrl(url_to_watch);
}
#Override
public void onPause()
{
super.onPause();
try
{
if ( webview != null )
{
webview.clearCache(true);
webview.getSettings().setAppCacheEnabled(false);
webview.stopLoading();
webview.destroy();
sendEmail ("in pause " , "");
webview = new WebView(this);
}
this.finish();
}
catch ( Exception e )
{
}
}
#Override
public void onDestroy()
{
super.onDestroy();
try
{
if ( webview != null )
{
webview = new WebView(this); // To try to reset the webview - didn't work.
}
}
catch ( Exception e )
{
}
}
#Override
public void onStop()
{
super.onStop();
FlurryAgent.onEndSession(this);
try
{
if ( webview != null )
{
webview.clearView();
webview.getSettings().setAppCacheEnabled(false);
webview.stopLoading();
webview.destroy();
sendEmail ("in stop " , "");
}
}
catch ( Exception e )
{
}
this.finish();
}
#Override
protected void onResume()
{
super.onResume();
try
{
webview.onResume();
}
catch ( Exception e )
{
}
}
#Override
protected void onRestart()
{
super.onRestart();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack())
{
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
// Subject , body
public void sendEmail( String subject , String body )
{
String[] params = new String[] { "http://www.problemio.com/problems/send_email_mobile.php", subject, body };
SendEmail task = new SendEmail();
task.execute(params);
}
//#Override
public void onPageFinished(WebView view, String url)
{
//super.onPageFinished(view, url);
view.clearCache(true);
}
public void onBackPressed ( )
{
final AlertDialog.Builder linkedin_builder = new AlertDialog.Builder(this);
linkedin_builder.setMessage("" +
"Go back to the home screen?")
.setCancelable(false)
.setNegativeButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
if ( webview != null )
{
webview.destroy();
}
Intent myIntent = new Intent(YoutubeActivity.this, MainActivity.class);
YoutubeActivity.this.startActivity(myIntent);
}
})
.setPositiveButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
})
;
AlertDialog alert = linkedin_builder.create();
alert.show();
}
#Override
protected void onStart()
{
super.onStart();
FlurryAgent.onStartSession(this, "4VYNFK3V6RCZ53CZ3J32");
}
}
Any thoughts on what might stop the audio from playing and what may be causing it?
Thank you!

try this, hope it helps:
#Override
public void onPause() {
myWebView.onPause();
myWebView.pauseTimers();//this may cause adMob to stop working
super.onPause();
}
#Override
public void onResume() {
super.onResume();
myWebView.resumeTimers();
myWebView.onResume();
}
#Override
protected void onDestroy() {
myWebView.destroy();
myWebView = null;
super.onDestroy();
}

You should call:
webView.loadUrl("about:blank");
It will destroy all audio/video as well as Javasript objects and stop all running functions on webview

Taken from https://stackoverflow.com/a/17690221/3032209:
You should call through to the WebView's onPause() and onResume() from your Activity's onPause() and onResume(), respectively.
Pauses any extra processing associated with this WebView and its
associated DOM, plugins, JavaScript etc. For example, if this WebView
is taken offscreen, this could be called to reduce unnecessary CPU or
network traffic. When this WebView is again "active", call onResume().

Nothing worked for me in some or all devices. This is the exact solution I guess. Worked for me well.
How to stop youtube video playing in Android webview?
alternatively for API >= 11 you can use
_webview.onPause(); on the activity's / fragment's onPause
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
_webview.onPause();
}

In activity's onDestroy() do:
#Override
protected void onDestroy() {
super.onDestroy();
webView.destroy();
}

You can do it using the method onPause() of your Activity :
#override
public void onPause() {
super.onPause();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
webview.onPause();
}
}
adding a validation for use in API >= 11 (Honeycomb)

private void destroyWebView() {
if (webView != null) {
webView.clearHistory();
webView.clearCache(false);
webView.loadUrl("about:blank");
webView.onPause();
webView.removeAllViews();
// webView.destroyDrawingCache();
// NOTE: This pauses JavaScript execution for ALL WebViews,
// do not use if you have other WebViews still alive.
// If you create another WebView after calling this,
// make sure to call mWebView.resumeTimers().
// webView.pauseTimers();//adMob will fail to load if called
webView.destroy();
webView = null;
}
}

Related

Quit popup and previous webpage are coming together when i press back button

when I press back button then Quit popup and previous page (in webview) are coming together. It should go previous page first, on the last page it should ask to quit.
Plzzzzzzzz help
MainActivity.java
package com.ravi.demoapp;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import android.app.Activity;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity{
private Fragment contentFragment;
String testDevice = "D0A04359EA1ECE9BA0CD4B6F457A9991";
String testDevice2 = "63C3530DA03C191310DB9AB8F0672E5C";
String testDevice3 = "801F2141A1DC3F743363AFDFDC42AF3A";
private InterstitialAd mInterstitialAd;
private AdView mAdView;
boolean displayAd = false;
WebView mainWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainWebView = (WebView) findViewById(R.id.mainWebView);
WebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mainWebView.loadUrl(this.getString(R.string.channel_url));
mAdView = (AdView) findViewById(R.id.ad_view);
// Create an ad request. Check your logcat output for the hashed device ID to
// get test ads on a physical device. e.g.
// "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(testDevice)
.addTestDevice(testDevice2)
.addTestDevice(testDevice3)
.build();
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
displayAd = true;
// View servername = findViewById(R.id.txt_List);
// RelativeLayout.LayoutParams layoutparams = (RelativeLayout.LayoutParams) servername.getLayoutParams();
// layoutparams.addRule(RelativeLayout.BELOW, mAdView.getId());
// layoutparams.removeRule(RelativeLayout.ALIGN_PARENT_TOP);
// servername.setLayoutParams(layoutparams);
}
#Override
public void onAdFailedToLoad(int errorCode) {
if (!displayAd) {
}
}
#Override
public void onAdClosed() {
// Proceed to the next level.
}
});
// Start loading the ad in the background.
mAdView.loadAd(adRequest);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
// Create the InterstitialAd and set the adUnitId (defined in values/strings.xml).
mInterstitialAd = newInterstitialAd();
loadInterstitial();
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
private InterstitialAd newInterstitialAd() {
InterstitialAd interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
}
#Override
public void onAdFailedToLoad(int errorCode) {
}
#Override
public void onAdClosed() {
// Proceed to the next level.
finish();
//goToNextLevel();
}
});
return interstitialAd;
}
private void showInterstitial() {
// Show the ad if it's ready. Otherwise toast and reload the ad.
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
finish();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void loadInterstitial() {
// Disable the next level button and load the ad.
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(testDevice)
.addTestDevice(testDevice2)
.addTestDevice(testDevice3)
.setRequestAgent("android_studio:ad_template").build();
mInterstitialAd.loadAd(adRequest);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if (event.getAction() == KeyEvent.ACTION_DOWN){switch(keyCode){case
KeyEvent.KEYCODE_BACK:
if (mainWebView.canGoBack()) {
mainWebView.goBack();
}else{
finish(); 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);
}
/*
* We call super.onBackPressed(); when the stack entry count is > 0. if it
* is instanceof EmpListFragment or if the stack entry count is == 0, then
* we prompt the user whether to quit the app or not by displaying dialog.
* In other words, from EmpListFragment on back press it quits the app.
*/
#Override
public void onBackPressed() {
onShowQuitDialog();
}
public void onShowQuitDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setMessage("Do You Want To Quit?");
builder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
showInterstitial();
}
});
builder.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
}
Actvity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.gms.ads.AdView
android:id="#+id/ad_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
ads:adUnitId="#string/banner_ad_server_list_unit_id"
ads:adSize="BANNER"/>
<WebView android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/ad_view"
android:id="#+id/mainWebView">
</WebView>
</RelativeLayout>
Do you have more Activities? Try this:
Button buttonBack;
buttonBack = (Button) findViewById(R.id.buttonBack);
//in your layout set android:id="#+id/buttonBack" (this is just an example)
buttonBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SecondActivity.this, MainActivity.class);
startActivity(intent);
}
});
With Stack implementation: If you want to go previous webpage by pressing back button you have to do two things.
Override onBackPressed
Saved your previous web page address on Stack.
Declare a String type stack
private Stack<String> stack = new Stack<>();
When new url is loading put the current url into stack. Like
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
stack.add(url);
}
}
Now, override onBackPressed
#Override
public void onBackPressed() {
if (stack.size() > 1 && stack != null) {
stack.pop();
load(stack.peek());
} else {
super.onBackPressed();
}
}
}
Here, load() is a methoad for loading webpage.
private void load(String urlToLoad) {
pd = new ProgressDialog(YourActivity.this);
pd.setMessage("Please wait Loading...");
pd.show();
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
webView.loadUrl(urlToLoad);
webView.setWebViewClient(new MyWebViewClient());
}
With WebView Native API: (As you describe)
#Override
public void onBackPressed() {
if(mainWebView.canGoBack())
mainWebView.goBack();
else
onShowQuitDialog();
}
No need to Override onKeyDown

Unable to Full Screen Youtube Video Inside Custom Webview

Update
I have updated my question to hide confidential code.
If still there is some confusion pls msg me in comments.
Question
I have written an custom Webview for playing youtube video embedded in my website to go full Screen.
But its still not Working..
.
kindly Help
public class MainActivity extends Activity implements OnClickListener {
final Context context = this;
private WebView webView;
private ImageButton btnrefresh;
private TextView txtrefresh;
private myWebChromeClient mWebChromeClient;
private Menu optionsMenu;
private WebChromeClient.CustomViewCallback customViewCallback;
private View mCustomView;
private FrameLayout customViewContainer;
#SuppressWarnings("deprecation")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Tushar
customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
//Tushar
//define button
btnrefresh = (ImageButton) findViewById(R.id.imageButton1);
btnrefresh.setOnClickListener(this);
btnrefresh.setVisibility(View.GONE);
//define textView
txtrefresh = (TextView)findViewById((R.id.textView1));
txtrefresh.setVisibility(View.GONE);
if(isConnected())
{
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setRenderPriority(RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setSaveFormData(true);
// webView.getSettings().setPluginState(PluginState.ON);
webView.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("mailto:")) {
sendEmail(url.substring(7));
return true;
}
return false;
}
});
initWebView(webView);
webView.loadUrl("http://Example.com/");
}
else
{
RelativeLayout rel = (RelativeLayout)findViewById(R.id.relativelayout1);
rel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
refresh();
}
});
btnrefresh.setVisibility(View.VISIBLE);
txtrefresh.setVisibility(View.VISIBLE);
Toast.makeText(getBaseContext(), "No Internet Connection !!", Toast.LENGTH_SHORT).show();
}
}
public boolean inCustomView() {
return (mCustomView != null);
}
public void hideCustomView() {
mWebChromeClient.onHideCustomView();
}
#Override
protected void onPause() {
super.onPause(); //To change body of overridden methods use File | Settings | File Templates.
webView.onPause();
}
#Override
protected void onResume() {
super.onResume(); //To change body of overridden methods use File | Settings | File Templates.
webView.onResume();
}
#Override
protected void onStop() {
super.onStop(); //To change body of overridden methods use File | Settings | File Templates.
if (inCustomView()) {
hideCustomView();
}
}
//tushar
class myWebChromeClient extends WebChromeClient {
private Bitmap mDefaultVideoPoster;
private View mVideoProgressView;
#Override
public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
onShowCustomView(view, callback); //To change body of overridden methods use File | Settings | File Templates.
}
#Override
public void onShowCustomView(View view,CustomViewCallback callback) {
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mCustomView = view;
webView.setVisibility(View.GONE);
customViewContainer.setVisibility(View.VISIBLE);
customViewContainer.addView(view);
customViewCallback = callback;
}
#Override
public View getVideoLoadingProgressView() {
if (mVideoProgressView == null) {
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
mVideoProgressView = inflater.inflate(R.layout.video_progress, null);
}
return mVideoProgressView;
}
#Override
public void onHideCustomView() {
super.onHideCustomView(); //To change body of overridden methods use File | Settings | File Templates.
if (mCustomView == null)
return;
webView.setVisibility(View.VISIBLE);
customViewContainer.setVisibility(View.GONE);
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
customViewContainer.removeView(mCustomView);
customViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
To achieve this you should:
Implement showCustomView and hideCustomView methods of WebChromeClient.
Set android:hardwareAccelerated="true" to your MainActivity in AndroidManifest.xml.
There are two classes that inherit the WebChromeClient in your code (myWebChromeClient and MyWebChromeClient). The first implements showCustomView and hideCustomView methods and it seems fully working with full-screen video. The second one don't. But you (accidentally?) set the second as WebChromeClient to your WebView.
To fix this just change the line
webView.setWebChromeClient(new MyWebChromeClient());
to
mWebChromeClient = new myWebChromeClient();
webView.setWebChromeClient(mWebChromeClient);
in your initWebView() method.
UPD:
To lock orientation on portrait in normal (not full-screen) mode add following line into onHideCustomView() method:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
To let the system decide the best orientation in full-screen mode add this line to onShowCustomView(View view, CustomViewCallback callback) method:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
Working Perfectly.
Tested on Android 9.0 version
This is the final thing worked
Set The setWebChromeClient on webview
mWebView.setWebChromeClient(new MyChrome());
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
WebView mWebView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webView);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebChromeClient(new MyChrome()); // here
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
if (savedInstanceState == null) {
mWebView.loadUrl("https://www.youtube.com/");
}
}
private class MyChrome extends WebChromeClient {
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
protected FrameLayout mFullscreenContainer;
private int mOriginalOrientation;
private int mOriginalSystemUiVisibility;
MyChrome() {}
public Bitmap getDefaultVideoPoster()
{
if (mCustomView == null) {
return null;
}
return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573);
}
public void onHideCustomView()
{
((FrameLayout)getWindow().getDecorView()).removeView(this.mCustomView);
this.mCustomView = null;
getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility);
setRequestedOrientation(this.mOriginalOrientation);
this.mCustomViewCallback.onCustomViewHidden();
this.mCustomViewCallback = null;
}
public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback)
{
if (this.mCustomView != null)
{
onHideCustomView();
return;
}
this.mCustomView = paramView;
this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
this.mOriginalOrientation = getRequestedOrientation();
this.mCustomViewCallback = paramCustomViewCallback;
((FrameLayout)getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1));
getWindow().getDecorView().setSystemUiVisibility(3846 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mWebView.restoreState(savedInstanceState);
}
}
In AndroidManifest.xml
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize" />
Solution Original Source
Referring to the code Sheharyar Ejaz has posted, I replaced 2 lines to improve the result.
THe first line I replaced is in onShowCustomView, so when user click Youtube fullscreen option of a video, the video will automatically expand into lansdcape fullscreen like native Youtube.
To achieve that, I replaced this line :
this.mOriginalOrientation = getRequestedOrientation();
with this line :
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
The second line I replaced is in onHideCustomView, so when user minimize the fullscreen video, it will revert into the phone's present layout.
What I do is I replaced this line :
this.mOriginalOrientation = getRequestedOrientation();
with this line :
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
But, quite different with the suggestion by erakitin, I did not set android:hardwareAccelerated="true" to my MainActivity/WebView Activity in AndroidManifest.xml.

Android metaio AREL launch url in app and NOT external browser

This is based on the Metaio sdk, but not sure the problem is dependant of it. I have created a basic AREL based Android app, using the Creator. On detection of marker I would like to load a url in a webview.
However when the marker is detected, I get the dialog of choosing what browser to open the url in.
How can I override that and make it open inside a webview in my app?
I tried using public boolean shouldOverrideUrlLoading(WebView view, String url) but it does not get called.
How can I make sure I get all the urls that are attempted to open by an Activity? so I can direct the calls to a webview..
In my activity I have this inside onCreate:
mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebViewClient(new WebViewHandler());
and this outside onCreate:
class WebViewHandler extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
Log.d("LEE","ping1!!!!!"+url);
mProgress.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url)
{
Log.d("LEE","ping2!!!!!"+url);
mProgress.setVisibility(View.GONE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
Log.d("LEE","Triggered url: !!!!!"+url);
}
}
You have a mistake in your override. You should be returning false at the end of shouldOverrideUrlLoading(). This will allow your WebView to handle the request instead of the system.
Have you tried to do it directly in AREL using arel.Media.openWebsite(url, false);
http://dev.junaio.com/arel/documentationArelJS/symbols/arel.Media.html#.openWebsite
You can edit arel code from creator directly
I solved it by overriding openWebsite() inside ARELInterpreterCallback like this...
//ARELViewActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.metaio.cloud.plugin.view.WebViewActivity;
import com.metaio.sdk.ARELActivity;
import com.metaio.sdk.jni.IARELInterpreterCallback;
public class ARELViewActivity extends ARELActivity {
protected ARELInterpreterCallback myARELCallback;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myARELCallback = new ARELInterpreterCallback();
if (mARELInterpreter != null)
mARELInterpreter.registerCallback(myARELCallback);
}
#Override
protected int getGUILayout() {
return 0;
}
class ARELInterpreterCallback extends IARELInterpreterCallback
{
#Override
public void onSDKReady()
{
loadARELScene();
}
#Override
public boolean openWebsite(String url, boolean openInExternalApp){
//url is set with arel.Media.openWebsite("template://item#", false); inside logic.js
if (url.contains("template://")) {
if (url.contains("item1")) {
urlSub = url.substring(14, url.length());
runOnUiThread(new Runnable() {
#Override
public void run() {
Intent i = new Intent(ARELViewActivity.this, WebViewActivity.class);
i.putExtra(getPackageName() + ".URL", "http://www.google.com.mx");
startActivity(i);
}
});
return true;
} else {
urlSub = url.substring(14, url.length());
runOnUiThread(new Runnable() {
#Override
public void run() {
Intent i = new Intent(ARELViewActivity.this, WebViewActivity.class);
i.putExtra(getPackageName() + ".URL", "http://www.yahoo.com.mx");
startActivity(i);
}
});
return true;
}
} else {
return false;
//return super.openWebsite(url, openInExternalApp);
}
}
}
}

webview shows everytime the content from the last loadurl() method

i have the Problem that i load a website with the loadDataWithBaseURL method. There i load a prepared internetsite in a webview. if i go back in my previous activity and start the webview activity it loads the same prepared website with loadDataWithBaseURL() method but i get a webview with twice the content. For example Hello World and the second Hello World.
My Code is the followed:
package de.http.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebBackForwardList;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebviewActivity extends Activity {
WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mywebview);
Bundle bundle= this.getIntent().getExtras();
String param1 = bundle.getString("Weburl");
getDetailWebsite(param1);
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setBuiltInZoomControls(true);
loadWebview();
}
public void loadWebview()
{
webview.clearView();
webview.loadDataWithBaseURL("http://branchenportal-schlitz.de", HttpHelperClass.htmlDetailWebsiteCode, "text/html", "UTF-8", HttpHelperClass.htmlDetailWebsiteCode);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
WebBackForwardList mWebBackForwardList = webview.copyBackForwardList();
String historyUrl = mWebBackForwardList.getItemAtIndex(mWebBackForwardList.getCurrentIndex()).getUrl();
if(historyUrl.contains("<html>"))
{
loadWebview();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
private void getDetailWebsite(String url)
{
try{
HttpHelperClass.executeHttpGetDetailWebsite(url,this);
}catch (Exception ex)
{
ex.printStackTrace();
}
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
if(url.contains("branchenportal-schlitz.de"))
{
view.clearHistory();
}
super.onPageFinished(view, url);
}
}
#Override
protected void onStop() {
webview.clearCache(true);
webview.clearView();
webview.clearHistory();
webview.destroy();
super.onStop();
}
}
Is there anybody who knows what iam doing wrong?
Thanks in advance.
With regards
OK well to trouble shoot this I would start by getting rid of (commenting out) all of your code below public boolean onKeyDown(int keyCode, KeyEvent event). Then you can see if its in your onCreate or not. But that's up to.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.buttons);
wb = new WebView(this);
wb.getSettings().setJavaScriptEnabled(true);
wb.setWebViewClient(new HelloWebViewClient());
final String urlToLoad = "http://www.yourWebsite.com";
wb.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
wb.loadUrl(urlToLoad);
}
start here then start adding your extra code back in.

android webview client activity indicator

I got the code for showing activity indicator in a webview. I checked more than one reference and still I couldn't get it working. Can you please help me to debug my code below?
The activity indicator is not coming with below code
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
final BaseActivity MyActivity = ReviewWebActivity.this;
setContentView(R.layout.review_web);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
ScannedProduct product = getReviewUrl();
reviewUrl = product.getReviewLink();
if (reviewUrl == null) {
String err = product.getErrorCode();
if(err.equals("")) err ="No Data Available for this product";
Toast.makeText(getApplicationContext(),
"No Data Available for this product", 1).show();
return;
}
webReview = (WebView) findViewById(R.id.webReview);
webReview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// Make the bar disappear after URL is loaded, and changes
// string to Loading...
MyActivity.setTitle("Loading...");
MyActivity.setProgress(progress * 1000); // tried with 100 also
}
});
webReview.setWebViewClient(new ReviewWebClient());
webReview.getSettings().setJavaScriptEnabled(true);
webReview.loadUrl(reviewUrl);
}
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class SandbarinFacebook extends Activity {
WebView mWebView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ProgressDialog pd = ProgressDialog.show(this, "", "Loading...",true);
mWebView = (WebView) findViewById(R.id.webkitWebView1);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if(pd!=null && pd.isShowing())
{
pd.dismiss();
}
}
});
mWebView.loadUrl("http://www.yahoo.co.in");
setTitle("Yahoo!");
}
}
Write below code in Activity's onCreate method.
webView.setWebChromeClient(new ChromeClient());
progress=ProgressDialog.show(this, "", "Loading...");
webView.loadUrl(url);
Create ChromeClient class in same activity.
private class ChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
if(newProgress >= 85) {
progress.dismiss();
}
super.onProgressChanged(view, newProgress);
}
}
Declare objects accordingly. Get back to me If you still face error. I will provide full source code.
I cannot post a comment because I don't have enough reputation points, but just a quick comment on the accepted answer: Check for null before checking if the dialog is showing. This will avoid the dreaded NPE.
if(pd != null && pd.isShowing()) { ... }
Kotlin snipet:
myProgressBar.show()
myWebView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
myProgressBar.hide()
}
}
Add this extension functions to your extensions file:
fun View.show() {
visibility = View.VISIBLE
}
fun View.hide() {
visibility = View.GONE
}

Categories

Resources