i was working on a webView had it working but the flash videos didn't work.
After a little bit of searching i found a webview code that displays videos.
webview video
this is my old code
private static final String LOG_TAG = "Web";
private WebView mWebView;
public static final String URL = "";
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.web);
mWebView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = mWebView.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
String turl = getIntent().getStringExtra(URL);
mWebView.loadUrl(turl);
;
}
#Override
public void onBackPressed() {
finish();
}
/**
* Provides a hook for calling "alert" from javascript. Useful for debugging
* your javascript.
*/
final class MyWebChromeClient extends WebChromeClient {
#Override
public boolean onJsAlert(WebView view, String url, String message,
JsResult result) {
Log.d(LOG_TAG, message);
result.confirm();
return true;
}
}
so i replaced it with the mainactivity from the source and added
String turl = getIntent().getStringExtra(URL);
and
public static final String URL = "";
and made some changes so it loads the class names i use
so now i've got this
private WebView webView;
public static final String URL = "";
private FrameLayout customViewContainer;
private WebChromeClient.CustomViewCallback customViewCallback;
private View mCustomView;
private myWebChromeClient mWebChromeClient;
private myWebViewClient mWebViewClient;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
webView = (WebView) findViewById(R.id.webView);
mWebViewClient = new myWebViewClient();
webView.setWebViewClient(mWebViewClient);
mWebChromeClient = new myWebChromeClient();
webView.setWebChromeClient(mWebChromeClient);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSaveFormData(true);
String turl = getIntent().getStringExtra(URL);
webView.loadUrl(turl);
}
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();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (inCustomView()) {
hideCustomView();
return true;
}
if ((mCustomView == null) && webView.canGoBack()) {
webView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
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(Web.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;
}
}
class myWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url); //To change body of overridden methods use File | Settings | File Templates.
}
}
i use this code for my button to open the url in webview
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Intent k = new Intent(this, Web.class);
k.putExtra(com.papers.test.Web.URL,
"http://www.telegraaf.mobi");
startActivity(k);
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.onlinekranten);
View secondButton = findViewById(R.id.button1);
secondButton.setOnClickListener(this);
}
in my old web.class this worked just fine but now when i press the button i'm getting a fc, can anyone help me out with this problem?
logcat
06-07 12:38:55.310: E/AndroidRuntime(3236): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.papers.test/com.papers.test.Web}: java.lang.NullPointerException
Its looks like your button needs to be declared
I like to do it above onCreate to use it any where
Button secondButton;
Related
Need some advice. I want to be able to redirect the user to a specific link in WebView. Example: we go to the first link and if it directs us to "google.com" then we will have to direct the user to "http://test.com". I made an implementation, put a redirect in shouldOverrideUrlLoading, however, after SplashScreen-loading image done its work, a white background appears and that's it. At the same time, if you remove the code for redirection, then after performing its work, the SplashScreen - loading image, the first link opens and the page from the Internet is displayed correctly. How do I redirect to other pages after opening the first one?
public class MainActivity extends AppCompatActivity {
private WebView webView;
private final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("http://test/start");
new TaskForRedirecting().execute();
}
public class TaskForRedirecting extends AsyncTask<Boolean, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Boolean... booleans) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Start loading here");
WebViewClient webViewClient = new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("google.com")) {
view.loadUrl("http://test1.com");
return false;
} else if (url.contains("yahoo.com")) {
view.loadUrl("http://test2.com");
return false;
} else {
}
return true;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request.getUrl().toString() == "google.com") {
view.loadUrl("http://test1.com");
view.loadUrl(request.getUrl().toString());
return false;
} else if (request.getUrl().toString() == "yahoo.com") {
view.loadUrl("http://test2.com");
return false;
}
return true;
}
};
webView.setWebViewClient(webViewClient);
Log.d(TAG, "Do in background: APP is Working!!!");
}
});
return false;
}
#Override
protected void onPostExecute(Boolean success) {
success = false;
if (success) {
Toast toast = Toast.makeText(MainActivity.this, "App is under maintenance!", Toast.LENGTH_SHORT);
toast.show();
} else {
Toast toast = Toast.makeText(MainActivity.this, "Let's start to work!", Toast.LENGTH_SHORT);
toast.show();
}
Log.d(TAG, "upload - final! ");
}
}
}
public class SplashScreenActivity extends AppCompatActivity {
long Delay = 6000;
private final String TAG = "SplashScreenActivity";
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash_screen);
new SplashScreen().execute();
}
public class SplashScreen extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void...voids) {
Timer RunSplash = new Timer();
TimerTask ShowSplash = new TimerTask() {
#Override
public void run() {
finish();
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(intent);
}
};
RunSplash.schedule(ShowSplash, Delay);
Log.d(TAG, "ShowSplash - final! ");
return null;
}
}
}
Your implementation needs to change a bit, we don't need to set the webview client inside an AsyncTask, instead, we can set it directly but it should be set before we call loadurl.
I have removed the asynctask, and set the client in onCreate method before calling loadUrl.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
WebViewClient webViewClient = new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("google.com")) {
view.loadUrl("http://test1.com");
return true;
} else if (url.contains("yahoo.com")) {
view.loadUrl("http://test2.com");
return true;
}
return false;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request.getUrl().toString() == "google.com") {
view.loadUrl("http://test1.com");
return true;
} else if (request.getUrl().toString() == "yahoo.com") {
view.loadUrl("http://test2.com");
return true;
}
return false;
}
};
webView.setWebViewClient(webViewClient);
webView.loadUrl("http://test/start");
}
UPDATE
Please check out the shouldOverrideUrlLoading Doc, You should return true when you want to cancel the current load, so when you want to load a different URL, then return true else return false to continue the current load. Returning false means the URL which is being loaded to the webview will continue, your custom URL will not be loaded.
I use following code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_web_view_play_youtube);
WebView w = (WebView) findViewById(R.id.w);
w.setWebChromeClient(new WebChromeClient());
w.setWebViewClient(new WebViewClient());
w.getSettings().setJavaScriptEnabled(true);
w.loadUrl("https://www.youtube.com/watch?v=gY-HZg1Uwpc");
}
i get following screenshot
In this screenshot, I could not see "fullScreen" button.
In your case, you have to first add FrameLayout in your XML file. After that
you have to implement two methods onShowCustomView and onHideCustomView of WebChromeClient as shown below:
FrameLayout customViewContainer = findViewById(R.id.customViewContainer);
webView.setWebChromeClient(new WebChromeClient() {
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
super.onShowCustomView(view,callback);
webView.setVisibility(View.GONE);
customViewContainer.setVisibility(View.VISIBLE);
customViewContainer.addView(view);
}
public void onHideCustomView () {
super.onHideCustomView();
webView.setVisibility(View.VISIBLE);
customViewContainer.setVisibility(View.GONE);
}
});
I should custom WebChromeClient#onShowCustomView and #onHideCustomView, following code will show fullscreen button:
public class TestWebViewPlayYoutube extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_web_view_play_youtube);
WebView w = (WebView) findViewById(R.id.w);
w.setWebChromeClient(new CrmClient());
w.setWebViewClient(new WebViewClient());
w.getSettings().setJavaScriptEnabled(true);
w.getSettings().setMediaPlaybackRequiresUserGesture(false);
w.loadUrl("https://www.youtube.com/watch?v=gY-HZg1Uwpc&autoplay=1");
}
class CrmClient extends WebChromeClient {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
}
#Override
public void onHideCustomView() {
super.onHideCustomView();
}
}
}
update
i improve my code, it will show fullscreen and hide fullscreen for html5 (for ex youtube video player), to use this code, you must make sure main/assets/test.mp4 exist
public class TestFullscreen2 extends Activity {
WebView w;
RelativeLayout container;
float dp;
static FrameLayout fullscreenV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_fullscreen2);
dp = getDp(this);
container = (RelativeLayout) findViewById(R.id.container);
w = (WebView) findViewById(R.id.w);
if (fullscreenV != null && fullscreenV.getParent() == null) {
w.setVisibility(GONE);
container.addView(fullscreenV);
}
w.setWebChromeClient(new CrmClient(this));
w.setWebViewClient(new WebViewClient());
w.getSettings().setJavaScriptEnabled(true);
w.getSettings().setMediaPlaybackRequiresUserGesture(false);
w.loadDataWithBaseURL("file:///android_asset/", "<video width='100%' height='auto' src='test.mp4' controls autoplay/>", "text/html", "utf-8", null);
}
#Override
protected void onDestroy() {
super.onDestroy();
w = null;
}
class CrmClient extends WebChromeClient {
Activity a;
public CrmClient(Activity a) {
this.a = a;
}
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
fullscreenV = (FrameLayout) view;
a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
#Override
public void onHideCustomView() {
super.onHideCustomView();
fullscreenV = null;
a.startActivity(new Intent(a, TestFullscreen2.class) {{
setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
}});
}
}
}
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment_view frag=new Fragment_view();
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.fragment,frag,"hey");
transaction.commit();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (inCustomView()) {
hideCustomView();
return true;
}
if ((mCustomView == null) && webView.canGoBack()) {
webView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Now here variables like inCustomView and hidecustomView are defined in another fragment. So how to add this back button support on activity while using variables from a fragment. So I basically want to implement back button support in Android activity while using the defined variables from a fragment.
public class Fragment_view extends Fragment{
private WebView webView;
private FrameLayout customViewContainer;
private WebChromeClient.CustomViewCallback customViewCallback;
private View mCustomView;
private myWebChromeClient mWebChromeClient;
private myWebViewClient mWebViewClient;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view= inflater.inflate(R.layout.fragment_view, container,false);
customViewContainer = (FrameLayout)view.findViewById(R.id.customViewContainer);
webView = (WebView)view. findViewById(R.id.webView);
mWebViewClient = new myWebViewClient();
webView.setWebViewClient(mWebViewClient);
mWebChromeClient = new myWebChromeClient();
webView.setWebChromeClient(mWebChromeClient);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSaveFormData(true);
String htmlFile = "file:///" + Environment.getExternalStorageDirectory()
.getPath()
+ "/video_nsta/index.html";
webView.loadUrl(htmlFile);
return view;
}
public boolean inCustomView() {
return (mCustomView != null);
}
public void hideCustomView() {
mWebChromeClient.onHideCustomView();
}
#Override
public void onPause() {
super.onPause();
webView.onPause();
}
#Override
public void onResume() {
super.onResume();
webView.onResume();
}
#Override
public void onStop() {
super.onStop();
if (inCustomView()) {
hideCustomView();
}
}
class myWebChromeClient extends WebChromeClient {
#Override
public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
onShowCustomView(view, callback);
}
#Override
public void onShowCustomView(View view,CustomViewCallback callback) {
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mCustomView = view;
webView.setVisibility(View.GONE);
customViewContainer.setVisibility(View.VISIBLE);
customViewContainer.addView(view);
customViewCallback = callback;
}
#Override
public void onHideCustomView() {
super.onHideCustomView();
if (mCustomView == null)
return;
webView.setVisibility(View.VISIBLE);
customViewContainer.setVisibility(View.GONE);
mCustomView.setVisibility(View.GONE);
customViewContainer.removeView(mCustomView);
customViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
class myWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
}
}
it's a matter of properly distributing the back button.
first create a fragment that can handle it:
public abstract class BackButtonFragment extends Fragment{
public boolean onBackPressed(){
return false; // defaults to false
}
}
then you change all your fragments to extend from BackButtonFragment.
Then on your activity you will use the appropriate callback for backbutton (remove the onKeyDown from your activity and use this instead):
#Override public void onBackPressed() {
Fragment f = getFragmentManager().findFragmentById(R.id.fragment);
if(f instanceof BackButtonFragment){
if(((BackButtonFragment)f).onBackPressed())
return;
}
// if fragment didn't use back button do the normal stuff
super.onBackPressed();
}
then inside each one of your fragments you will override the method onBackPressed and return the correct value true or false depending on your needs.
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.
I got a progress bar, a Full screen video playback method (for playing youtube videos in full-screen), and public boolean shouldOverrideUrlLoading for handling URL's within the WebView but i cannot get all of the three to work together, i tried the following three approaches and it seems like i need duplicate webviewClient and webChromeclients to make everything work which depend on them
Approach 1 - Progress Bar is not working (stuck on 0%)
public class MainActivity extends Activity {
private WebView mWebView;
private EditText urlEditText;
private ProgressBar progress;
// FULL-SCREEN VIDEO-1
private LinearLayout mContentView;
private FrameLayout mCustomViewContainer;
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
private WebChromeClient mWebChromeClient;
// FULL-SCREEN VIDEO-1
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// FULL-SCREEN VIDEO-2
mContentView = (LinearLayout) findViewById(R.id.linearlayout);
mWebView = (WebView) findViewById(R.id.webView);
mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);
mWebChromeClient = new WebChromeClient() {
#Override
public void onShowCustomView(View view,
WebChromeClient.CustomViewCallback callback) {
// if a view already exists then immediately terminate the new
// one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// hide main browser view
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
#Override
public void onHideCustomView() {
if (mCustomView == null)
return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
}
};
// FULL-SCREEN VIDEO-2
WebSettings webSettings = mWebView.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new HelloWebViewClient());
// Download manager
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
// **//
// URL BAR AND PROGRESS BAR
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
urlEditText = (EditText) findViewById(R.id.urlField);
// Use Done/search button in keyboard as go button
urlEditText.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
// Toast.makeText(getApplicationContext(), "some key pressed",
// Toast.LENGTH_LONG).show();
String url = urlEditText.getText().toString();
if (url.endsWith(".ac") || url.endsWith(".ac.uk")
|| url.endsWith(".ad") || url.endsWith(".zw")) {
if (!url.startsWith("http://")
&& !url.startsWith("https://")) {
url = "http://" + url;
}
} else
url = "https://www.google.com/search?q="
+ url.replace(" ", "+");// Prefix (replace spaces
// with a '+' sign)
mWebView.loadUrl(url);
if (validateUrl(url)) {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
MainActivity.this.progress.setProgress(10);
}
return false;
}
private boolean validateUrl(String url) {
return true;
}
});
// **//
}
private class MyWebViewClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
MainActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url) {
webview.setWebChromeClient(mWebChromeClient);
webview.loadUrl(url);
return true;
}
}
// FULL-SCREEN VIDEO-3
#Override
protected void onStop() {// plays video outside frame on back button and
// prevents from going back
super.onStop();
if (mCustomView != null) {
if (mCustomViewCallback != null)
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
#Override
public void onBackPressed() {// hide custom view (in which the video plays)
// on back button
super.onBackPressed();
if (mCustomView != null) {
mWebChromeClient.onHideCustomView();
} else {
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {// prevents the
// custom view from
// running in
// background when
// app is closed
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
// FULL-SCREEN VIDEO-3
}
}
Approach 2 - Full Screen Not working
public class MainActivity extends Activity {
private WebView mWebView;
private EditText urlEditText;
private ProgressBar progress;
// FULL-SCREEN VIDEO-1
private LinearLayout mContentView;
private FrameLayout mCustomViewContainer;
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
private WebChromeClient mWebChromeClient;
// FULL-SCREEN VIDEO-1
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// FULL-SCREEN VIDEO-2
mContentView = (LinearLayout) findViewById(R.id.linearlayout);
mWebView = (WebView) findViewById(R.id.webView);
mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);
mWebChromeClient = new WebChromeClient() {
#Override
public void onShowCustomView(View view,
WebChromeClient.CustomViewCallback callback) {
// if a view already exists then immediately terminate the new
// one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// hide main browser view
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
#Override
public void onHideCustomView() {
if (mCustomView == null)
return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
}
};
// FULL-SCREEN VIDEO-2
WebSettings webSettings = mWebView.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new HelloWebViewClient());
mWebView.setWebChromeClient(new mWebChromeClient());
// Download manager
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
// **//
// URL BAR AND PROGRESS BAR
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
urlEditText = (EditText) findViewById(R.id.urlField);
// Use Done/search button in keyboard as go button
urlEditText.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
// Toast.makeText(getApplicationContext(), "some key pressed",
// Toast.LENGTH_LONG).show();
String url = urlEditText.getText().toString();
if (url.endsWith(".ac") || url.endsWith(".ac.uk")
|| url.endsWith(".ad") || url.endsWith(".zw")) {
if (!url.startsWith("http://")
&& !url.startsWith("https://")) {
url = "http://" + url;
}
} else
url = "https://www.google.com/search?q="
+ url.replace(" ", "+");// Prefix (replace spaces
// with a '+' sign)
mWebView.loadUrl(url);
if (validateUrl(url)) {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
MainActivity.this.progress.setProgress(10);
}
return false;
}
private boolean validateUrl(String url) {
return true;
}
});
// **//
}
private class mWebChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
MainActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url) {
webview.loadUrl(url);
return true;
}
}
// FULL-SCREEN VIDEO-3
#Override
protected void onStop() {// plays video outside frame on back button and
// prevents from going back
super.onStop();
if (mCustomView != null) {
if (mCustomViewCallback != null)
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
#Override
public void onBackPressed() {// hide custom view (in which the video plays)
// on back button
super.onBackPressed();
if (mCustomView != null) {
mWebChromeClient.onHideCustomView();
} else {
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {// prevents the
// custom view from
// running in
// background when
// app is closed
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
// FULL-SCREEN VIDEO-3
}
}
Approach 3 - shouldOverrideUrlLoading not working
public class MainActivity extends Activity {
private WebView mWebView;
private EditText urlEditText;
private ProgressBar progress;
// FULL-SCREEN VIDEO-1
private LinearLayout mContentView;
private FrameLayout mCustomViewContainer;
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
private WebChromeClient mWebChromeClient;
// FULL-SCREEN VIDEO-1
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// FULL-SCREEN VIDEO-2
mContentView = (LinearLayout) findViewById(R.id.linearlayout);
mWebView = (WebView) findViewById(R.id.webView);
mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);
mWebChromeClient = new WebChromeClient() {
#Override
public void onShowCustomView(View view,
WebChromeClient.CustomViewCallback callback) {
// if a view already exists then immediately terminate the new
// one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// hide main browser view
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
#Override
public void onHideCustomView() {
if (mCustomView == null)
return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
}
};
// FULL-SCREEN VIDEO-2
WebSettings webSettings = mWebView.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebChromeClient(new HelloWebViewClient());
// Download manager
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
// **//
// URL BAR AND PROGRESS BAR
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
urlEditText = (EditText) findViewById(R.id.urlField);
// Use Done/search button in keyboard as go button
urlEditText.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
// Toast.makeText(getApplicationContext(), "some key pressed",
// Toast.LENGTH_LONG).show();
String url = urlEditText.getText().toString();
if (url.endsWith(".ac") || url.endsWith(".ac.uk")
|| url.endsWith(".ad") || url.endsWith(".zw")) {
if (!url.startsWith("http://")
&& !url.startsWith("https://")) {
url = "http://" + url;
}
} else
url = "https://www.google.com/search?q="
+ url.replace(" ", "+");// Prefix (replace spaces
// with a '+' sign)
mWebView.loadUrl(url);
if (validateUrl(url)) {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
MainActivity.this.progress.setProgress(10);
}
return false;
}
private boolean validateUrl(String url) {
return true;
}
});
// **//
}
private class HelloWebViewClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
MainActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
private class HelloWebViewClient1 extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url) {
webview.setWebChromeClient(mWebChromeClient);
webview.loadUrl(url);
return true;
}
}
// FULL-SCREEN VIDEO-3
#Override
protected void onStop() {// plays video outside frame on back button and
// prevents from going back
super.onStop();
if (mCustomView != null) {
if (mCustomViewCallback != null)
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
#Override
public void onBackPressed() {// hide custom view (in which the video plays)
// on back button
super.onBackPressed();
if (mCustomView != null) {
mWebChromeClient.onHideCustomView();
} else {
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {// prevents the
// custom view from
// running in
// background when
// app is closed
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
// FULL-SCREEN VIDEO-3
}
}