html video not playing in android webview - android

i am working with android webview and here i stucked with the videos .Actually i am trying to play a video that is in asset folder but its not playing.
Here i have gone through all the links and solutions but nothing is working for me like-
[link1][1]
https://code.google.com/p/html5webview/source/browse/trunk/HTML5WebView/src/org/itri/html5webview/TestHTML5WebView.java
and
[link2][2]
http://www.mocoven.com/blog/?p=199
and below i am attaching the code-
//Html5webview
package com.example.jbb_video_play;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
public class HTML5WebView extends WebView {
private Context mContext;
private MyWebChromeClient mWebChromeClient;
private View mCustomView;
private FrameLayout mCustomViewContainer;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
private FrameLayout mContentView;
private FrameLayout mBrowserFrameLayout;
private FrameLayout mLayout;
static final String LOGTAG = "HTML5WebView";
#SuppressLint("NewApi")
private void init(Context context) {
mContext = context;
Activity a = (Activity) mContext;
mLayout = new FrameLayout(context);
mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(a).inflate(R.layout.custom_screen, null);
mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(R.id.main_content);
mCustomViewContainer = (FrameLayout) mBrowserFrameLayout.findViewById(R.id.fullscreen_custom_content);
mLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
mWebChromeClient = new MyWebChromeClient();
setWebChromeClient(mWebChromeClient);
setWebViewClient(new MyWebViewClient());
// Configure the webview
WebSettings s = getSettings();
s.setBuiltInZoomControls(true);
s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
s.setUseWideViewPort(true);
s.setAllowContentAccess(true);
s.setAllowFileAccess(true);
s.setAllowUniversalAccessFromFileURLs(true);
s.setAllowFileAccessFromFileURLs(true);
s.setMediaPlaybackRequiresUserGesture(true);
s.setNeedInitialFocus(true);
s.setSaveFormData(true);
s.setUserAgentString(getUrl());
s.setLoadsImagesAutomatically(true);
s.setBlockNetworkLoads(false);
s.setBlockNetworkImage(false);
s.setDatabaseEnabled(true);
s.setJavaScriptCanOpenWindowsAutomatically(true);
s.setJavaScriptEnabled(true);
s.setSupportMultipleWindows(true);
s.setLoadWithOverviewMode(true);
s.setSavePassword(true);
s.setSaveFormData(true);
s.setJavaScriptEnabled(true);
// enable navigator.geolocation
s.setGeolocationEnabled(true);
// s.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");
// enable Web Storage: localStorage, sessionStorage
s.setDomStorageEnabled(true);
mContentView.addView(this);
}
public HTML5WebView(Context context) {
super(context);
init(context);
}
public HTML5WebView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public HTML5WebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public FrameLayout getLayout() {
return mLayout;
}
public boolean inCustomView() {
return (mCustomView != null);
}
public void hideCustomView() {
mWebChromeClient.onHideCustomView();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if ((mCustomView == null) && canGoBack()){
goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private class MyWebChromeClient extends WebChromeClient {
private Bitmap mDefaultVideoPoster;
private View mVideoProgressView;
#Override
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
{
//Log.i(LOGTAG, "here in on ShowCustomView");
HTML5WebView.this.setVisibility(View.GONE);
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mCustomViewContainer.addView(view);
mCustomView = view;
mCustomViewCallback = callback;
mCustomViewContainer.setVisibility(View.VISIBLE);
}
#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();
HTML5WebView.this.setVisibility(View.VISIBLE);
//Log.i(LOGTAG, "set it to webVew");
}
#Override
public Bitmap getDefaultVideoPoster() {
//Log.i(LOGTAG, "here in on getDefaultVideoPoster");
if (mDefaultVideoPoster == null) {
mDefaultVideoPoster = BitmapFactory.decodeResource(
getResources(), R.drawable.ic_launcher);
}
return mDefaultVideoPoster;
}
#Override
public View getVideoLoadingProgressView() {
//Log.i(LOGTAG, "here in on getVideoLoadingPregressView");
if (mVideoProgressView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
}
return mVideoProgressView;
}
#Override
public void onReceivedTitle(WebView view, String title) {
((Activity) mContext).setTitle(title);
}
#Override
public void onProgressChanged(WebView view, int newProgress) {
((Activity) mContext).getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress*100);
}
#Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(LOGTAG, "shouldOverrideUrlLoading: "+url);
// don't override URL so that stuff within iframe can work properly
// view.loadUrl(url);
return false;
}
}
static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
and
//MainActivity
public class MainActivity extends Activity {
HTML5WebView mWebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebView = new HTML5WebView(this);
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
} else {
try
{
AssetManager m=this.getAssets();
InputStream ios= m.open("nasa.html");
BufferedReader br=new BufferedReader(new InputStreamReader(ios));
StringBuffer nb=new StringBuffer();
String line="";
while((line=br.readLine())!=null)
{
nb.append(line);
}
String final_data=nb.toString();
//mWebView.loadDataWithBaseURL("file:///android_asset/", final_data, "text/html", "utf-8", null);
// mWebView.loadUrl("http://freebsd.csie.nctu.edu.tw/~freedom/html5/");
mWebView.loadUrl("file:///android_asset/nasa.html");
}
catch (Exception e) {
// TODO: handle exception
}
}
setContentView(mWebView.getLayout());
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
public void onStop() {
super.onStop();
mWebView.stopLoading();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (mWebView.inCustomView()) {
mWebView.hideCustomView();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
}
//html file in asset folder
<!DOCTYPE html>
<head></head>
<body>
<video id="video" height="240" width="360" controls="controls" >
<source src="clipcanvas_14348_offline.mp4" type="video/mp4">
</video>
</body>
<footer>
</footer>
and link of video
http://www.clipcanvas.com/a/video-clip-downloads/
please suggest me any workable solution,thanks

It happens when video is in a div, you should add these lines in your code:
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setAppCachePath(getApplicationContext().getFilesDir().getAbsolutePath() + "/cache");
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDatabasePath(getApplicationContext().getFilesDir().getAbsolutePath() + "/databases");

Next to the WebViewClient, you should also add WebChromeClient to the WebView.
webView.setWebViewClient(new MyWebViewClient());
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://118.102.182.53:9080/swami/index.html");
For Android version 3.x you can also set hardwareAccelerated="true in the AndroidManifest.xml.

Just add
android:hardwareAccelerated="true" for your activity tag in AndroidManifest.xml

Related

My Webview in fragment always refresh when i switch my tab from one to other

I want to save instant of my fragment and then restore back on reopening the tab. when switching from one tab to other.
here is my fragment code:
package com.mhm.universityofwah.fragments;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.mhm.universityofwah.R;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
import jp.co.recruit_lifestyle.android.widget.WaveSwipeRefreshLayout;
public class WebFragment extends Fragment implements WaveSwipeRefreshLayout.OnRefreshListener {
private WaveSwipeRefreshLayout swipeRefreshLayout;
private WebView mWebView;
private Activity context;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setRetainInstance(true);
View view = inflater.inflate(R.layout.fragment_avicenna, container, false);
mWebView = (WebView) view.findViewById(R.id.webview);
swipeRefreshLayout = (WaveSwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
swipeRefreshLayout.setOnRefreshListener((WaveSwipeRefreshLayout.OnRefreshListener) WebFragment.this);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
swipeRefreshLayout.setRefreshing(true);
}
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
}
});
BottomNavigationView bottomNavigationView=view.findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListner);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(false);
mWebView.setWebViewClient(new Callback());
if(savedInstanceState==null){
loadWebsite();
}
return view;
}
private BottomNavigationView.OnNavigationItemSelectedListener navListner=
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_refresh:
mWebView.reload();
break;
case R.id.nav_back:
if(mWebView.canGoBack()){
mWebView.goBack();
}
break;
case R.id.nav_forward:
if(mWebView.canGoForward()){
mWebView.goForward();
}
break;
}
return true;
}
};
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void loadWebsite() {
ConnectivityManager cm = (ConnectivityManager) Objects.requireNonNull(getActivity()).getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
mWebView.loadUrl("http://uow.edu.pk");
} else {
Toast.makeText(Objects.requireNonNull(getActivity()).getApplicationContext(), "Please Check Network Connection!", Toast.LENGTH_SHORT).show();
swipeRefreshLayout.setRefreshing(false);
}
}
public class Callback extends WebViewClient {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(Objects.requireNonNull(getActivity()).getApplicationContext(), "Please Check Network Connection!", Toast.LENGTH_SHORT).show();
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".pdf")) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}else if (url.contains("mailto:")) {
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}else if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
return true;
}else {
view.loadUrl(url);
return true;
}
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
swipeRefreshLayout.setRefreshing(true);
}
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
}
}
#Override
public void onRefresh() {
mWebView.reload();
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
}
}
#Override
public void onSaveInstanceState(#NotNull Bundle outState )
{
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public boolean onKey(View v, int keyCode, KeyEvent event ) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
Objects.requireNonNull(getActivity()).finish();
}
return true;
}
}
// here your code
return false;
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
this.context = (Activity) context;
}
}
I have 4 tabs but when i switch from one tab to other and come back to first one, it always reload. i tried every thing but my problem is not solved. Please help me to get this thing done.
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setRetainInstance(true);
if(view == null){
view = inflater.inflate(R.layout.fragment_avicenna, container, false);
mWebView = (WebView) view.findViewById(R.id.webview);
swipeRefreshLayout = (WaveSwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
swipeRefreshLayout.setOnRefreshListener((WaveSwipeRefreshLayout.OnRefreshListener) WebFragment.this);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
swipeRefreshLayout.setRefreshing(true);
}
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
}
});
BottomNavigationView bottomNavigationView=view.findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListner);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(false);
mWebView.setWebViewClient(new Callback());
if(savedInstanceState==null){
loadWebsite();
}
}
return view;
}
please make view a global variable and add null check when your onCreate view recalls it recreates the view so add check that if view != null then only return already initialized view instead of creating again

Go back to previous page one back key press Android WebView Fragment

I am using Navigation drawer activity and have 5 fragments, each and every fragment uses WebView to open webpage. Before I was using just one MainActivity which just opened one site and was able to go back to previous opened page easily but now I can't find anything that will let me do this. I am using this code currently in my fragments, I am using the code to go back from here and whenever I open a fragment, app just force-closes.
package com.science.s11;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
public class ask extends Fragment {
public WebView mWebView;
public ProgressBar progressBar;
public LinearLayout layoutProgress;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.ampproject, container, false);
mWebView = (WebView) v.findViewById(R.id.aboutuswebViewask);
progressBar = (ProgressBar) v.findViewById(R.id.progressBarask);
layoutProgress = (LinearLayout) v.findViewById(R.id.layoutProgressask);
mWebView.setVisibility(View.GONE);
mWebView.setOnKeyListener(new View.OnKeyListener()
{
#Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
WebSettings settings = mWebView.getSettings();
settings.setSupportMultipleWindows(true);
settings.setBuiltInZoomControls(false);
settings.setSupportZoom(false);
settings.setDisplayZoomControls(false);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
mWebView.setVisibility(View.VISIBLE);
layoutProgress.setVisibility(View.GONE);
progressBar.setIndeterminate(true);
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
layoutProgress.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(false);
super.onPageStarted(view, url, favicon);
}
});
if (isOnline()) {
mWebView.loadUrl("http://google.com");
} else {
mWebView.loadUrl("file:///android_asset/cti.html");
}
return v;
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnected());
}}
Can you guys please help me?
Try this, its simple and works fine.
In all of your 5 Fragments, set the variable to public static:
public static WebView mWebView;
In your Mainactivity:
#Override
public void onBackPressed() {
if (Fragment_1.mWebView!= null) {
if (Fragment_1.mWebView.canGoBack()) {
Fragment_1.mWebView.goBack();
} else {
// do when mWebView cant go back anymore
}
}
if (Fragment_2.mWebView!= null){
if (Fragment_2.mWebView.canGoBack()) {
Fragment_2.mWebView.goBack();
} else {
// do when mWebView cant go back anymore
}
}
if (Fragment_3.mWebView!= null){
if (Fragment_3.mWebView.canGoBack()) {
Fragment_3.mWebView.goBack();
} else {
// do when mWebView cant go back anymore
}
}
if (Fragment_4.mWebView!= null){
if (Fragment_4.mWebView.canGoBack()) {
Fragment_4.mWebView.goBack();
} else {
// do when mWebView cant go back anymore
}
}
//and so on......
}
Try this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
you can make a base fragment like this
public abstract class BaseFragments extends Fragment {
abstract public int setContentView();
public void replaceFragment(Context context, Fragment fragment) {
((BaseActivity) context).getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment).commit();
}
#Override
public void onResume() {
super.onResume();
// preferencesUtility.setuserData(context, userdata);
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP
&& keyCode == KeyEvent.KEYCODE_BACK) {
// Toast.makeText(context, "clicked", Toast.LENGTH_LONG)
// .show();
backPressed();
return true;
}
return false;
}
});
}
protected abstract void backPressed();
}
and override onBackPressed()in your fragment something like this
public class TestFragment extends BaseFragments {
#Override
public int setContentView() {
return R.layout.weblayout;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.weblayout, container, false);
cabmoneyview = (WebView) rootView.findViewById(R.id.webview);
return rootView;
}
#Override
protected void backPressed() {
// TODO Auto-generated method stub
}
}

Create custom WebView Cordova Android 5.1.0

I need to create 3 custom Cordova WebView using Cordova Android 5.1.0. Previously I have succeeded to create custom WebView using Cordova Android 2.7 by modifying/overwriting file platform/android/src/com/hello/helloapp.java. Below is my previous code:
package com.hello.helloapp;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewClient;
import com.hello.helloapp.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.LinearLayout;
public class HelloApp extends Activity implements CordovaInterface {
int SCREEN_WIDTH;
int SCREEN_HEIGHT;
static String parentUrl;;
CordovaWebView view2;
CordovaWebView view1;
CordovaWebView view3;
static String htmlStr;
LinearLayout layout;
boolean connectionStatus;
private final ExecutorService threadPool = Executors.newCachedThreadPool();
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Config.init(this);
this.getScreenSize();
view1 = (CordovaWebView) findViewById(R.id.local_web_view);
view1.loadUrl("file:///android_asset/www/index.html");
view2 = (CordovaWebView) findViewById(R.id.external_web_view);
view2.loadUrl("http://google.com");
view2.requestFocus(WebView.FOCUS_DOWN);
view2.setWebViewClient(new MyWebViewClient(this, view2));
view3 = (CordovaWebView) findViewById(R.id.articles_web_view);
view3.loadUrl("file:///android_asset/www/articles.html");
view2.addJavascriptInterface(this, "GetHTML");
layout = (LinearLayout) findViewById(R.id.progressBar);
if (!isTabletDevice(this)) {
super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
if (isAirplaneModeOn(this)) {
connectionStatus = false;
} else if (isNetworkOnline()) {
connectionStatus = true;
} else
connectionStatus = false;
System.out.println(connectionStatus);
if (!connectionStatus) {
view2.setVisibility(View.GONE);
view3.loadUrl("file:///android_asset/www/articles.html");
view3.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isNetworkOnline() {
boolean status = false;
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(0);
NetworkInfo netInfo1 = cm.getNetworkInfo(1);
if ((netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED)
|| (netInfo1 != null && netInfo1.getState() == NetworkInfo.State.CONNECTED)) {
status = true;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
System.out.println(status);
return status;
}
public static boolean isTabletDevice(Context activityContext) {
// Verifies if the Generalized Size of the device is XLARGE to be
// considered a Tablet
boolean xlarge = ((activityContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE);
// If XLarge, checks if the Generalized Density is at least MDPI
// (160dpi)
if (xlarge) {
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = (Activity) activityContext;
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
// DENSITY_TV=213, DENSITY_XHIGH=320
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
|| metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
|| metrics.densityDpi == DisplayMetrics.DENSITY_TV
|| metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
// Yes, this is a tablet!
return true;
}
}
// No, this is not a tablet!
return false;
}
#SuppressWarnings("deprecation")
private static boolean isAirplaneModeOn(Context context)
throws SettingNotFoundException {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
#Override
public Activity getActivity() {
return this;
}
#Override
public ExecutorService getThreadPool() {
return threadPool;
}
public void getScreenSize() {
Display display = getWindowManager().getDefaultDisplay();
SCREEN_WIDTH = display.getWidth();
SCREEN_HEIGHT = display.getHeight();
}
public class MyWebViewClient extends CordovaWebViewClient {
private CordovaInterface cordova;
public MyWebViewClient(CordovaInterface ctx, CordovaWebView app) {
super(ctx, app);
this.cordova = ctx;
}
#Override
public void onReceivedError(WebView arg0, int arg1, String arg2,
String arg3) {
arg0.loadUrl("javascript:navigator.notification.alert(\"Sorry,the network is not available.\",\"null\");");
}
public boolean shouldOverrideUrlLoading(final WebView view, String url) {
connectionStatus = isNetworkOnline();
System.out.println(connectionStatus);
if (connectionStatus) {
System.out.println("---------shouldoverride-------" + url);
if (url.contains(".pdf")&& !url.contains("originUrl")) {
System.out.println(HelloApp.htmlStr);
view1.loadUrl("javascript:downloadFile(\"" + url + "\",\""
+ HelloApp.htmlStr + "\",\"" + HelloApp.parentUrl
+ "\");");
return false;
} else if (url.contains("search?")
&& HelloApp.parentUrl
.equalsIgnoreCase("http://google.com/")) {
System.out.println("parenturl");
url = url.concat("&showAll=false");
view2.loadUrl(url);
return false;
} else {
return false;
}
} else {
view1.loadUrl("javascript:navigator.notification.alert(\"Sorry,the network is not available.\",\"null\");");
return true;
}
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
layout.setVisibility(View.VISIBLE);
if (url.contains(".pdf")) {
}else {
HelloApp.parentUrl = url;
if (view2.canGoBack() && view2.canGoForward()) {
view1.loadUrl("javascript:callBackFun(\"F_1B_1\")");
} else if (view2.canGoForward()) {
view1.loadUrl("javascript:callBackFun(\"F_1\")");
} else if (view2.canGoBack()) {
view1.loadUrl("javascript:callBackFun(\"B_1\")");
}
}
super.onPageStarted(view, url, favicon);
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.contains(".pdf")) {
} else {
System.out.println("----------------" + url);
view2.loadUrl("javascript: GetHTML.getHtml(document.body.innerHTML);");
view2.loadUrl("javascript: $(\".content-pricing\").hide()");
view2.loadUrl("javascript: $(\"a[href*='mailto']\").removeAttr('href');");
System.out.println("REMOVE------------------------>>>");
view2.loadUrl("javascript:$('head').append('<style>#coverImageUrl, .content-pricing, .price-disclaimer {display : none;}</style>')");
layout.setVisibility(View.INVISIBLE);
}
}
}
public Object onMessage(String arg0, Object arg1) {
return null;
}
#Override
public void setActivityResultCallback(CordovaPlugin arg0) {
}
#Override
public void startActivityForResult(CordovaPlugin arg0, Intent arg1, int arg2) {
}
#JavascriptInterface
public void getHtml(String html) {
this.htmlStr = html.replace("\"", "\'").replaceAll("\n", "").replaceAll("%22", "\'").trim();
}
}
Now there is lots of update in Cordova, they also update there CordovaWebView code. After updating Cordova Android version from 2.7 to 5.1.0, app is crashed. I tried to use SystemWebView instead of CordovaWebView but still get error and crashes as some of methods are missing in SystemWebView.
Please help how can I update previous WebView code or create new multiple WebView in Cordova 5.1.0.
Thanks!!
This is how I implemented new Cordova library in my existing project.
public class MyWebViewFragment extends Fragment{
private Activity mActivity;
private SystemWebView syswvPhoneWebview;
private CordovaWebView wvPhoneWebview;
#Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity = (Activity) context;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (mView == null) {
mView = inflater.inflate(R.layout.fragment_web_view, null);
setLayoutViews(mView);
}
return mView;
}
private void setLayoutViews(View mView) {
syswvPhoneWebview = (SystemWebView) mView.findViewById(R.id.wvPhoneWebview);
wvPhoneWebview = new CordovaWebViewImpl(new SystemWebViewEngine(syswvPhoneWebview));
wvPhoneWebview.init((CordovaInterface) getParentFragment(), parser.getPluginEntries(), parser.getPreferences());
syswvPhoneWebview.setWebContentsDebuggingEnabled(true);
syswvPhoneWebview.getSettings().setLoadsImagesAutomatically(true);
syswvPhoneWebview.getSettings().setJavaScriptEnabled(true);
syswvPhoneWebview.getSettings().setDomStorageEnabled(true);
syswvPhoneWebview.getSettings().setBuiltInZoomControls(true);
syswvPhoneWebview.getSettings().setSupportZoom(true);
wvPhoneWebview.loadUrl("www.google.com");
SystemWebViewEngine systemWebViewEngine = (SystemWebViewEngine) wvPhoneWebview.getEngine();
syswvPhoneWebview.setWebViewClient(new DocumentViewClient(systemWebViewEngine, mActivity));
}
}
now webviewclient code.
public class DocumentViewClient extends SystemWebViewClient {
private final Activity activity;
public DocumentViewClient(SystemWebViewEngine parentEngine, Activity activity) {
super(parentEngine);
this.activity = activity;
}
}

can't play .mp4 file from Url link

I am working to play video file from a URL link. My URL looks like:
// this not works
https://vimeo.com/81995018
I am tested below link it work, what some answer here.
// it works fine
String LINK = "http://www.boisestatefootball.com/sites/default/files/videos/original/01%20-%20coach%20pete%20bio_4.mp4";
When i run with my link get an error in log cat which looks :
12-18 12:25:19.207: D/MediaPlayer(1578): Couldn't open file on client side, trying server side
12-18 12:25:19.217: E/MediaPlayer(1578): error (1, -2147483648)
12-18 12:25:19.277: E/MediaPlayer(1578): Error (1,-2147483648)
12-18 12:25:19.277: D/VideoView(1578): Error: 1,-2147483648
My Activity class as follows:
public class MainActivity extends Activity {
Context context = this;
VideoView videoView;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// it works fine
// String LINK =
// "http://www.boisestatefootball.com/sites/default/files/videos/original/01%20-%20coach%20pete%20bio_4.mp4";
// this not works :(
String LINK = "https://vimeo.com/81995018";
videoView = (VideoView) findViewById(R.id.videoView_test);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoView);
mc.setMediaPlayer(videoView);
Uri video = Uri.parse(LINK);
videoView.setMediaController(mc);
videoView.setVideoURI(video);
videoView.requestFocus();
videoView.start();
}
}
I am also trying to get the codec/format/specification of the given video link,to check whether my Android 2.3.4 Sony XPeria-New run it or not. But can't get this also.
Need someone's super knock. Thank you.
This Link shows what files Android phones and tablets support, with both codec and filename extension information provided. However, an Android application can use media codecs either provided by any Android-powered device, or additional media codecs developed by third-party companies. Therefore, if you want to play videos on Android, find a multi-format video player or convert videos to Android compatible formats.
See this Android Supported Media Formats http://developer.android.com/guide/appendix/media-formats.html.
This is only for running VimeoVideo
Use this two class.
package com.example.newsolution;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
public class Test extends Activity {
HTML5WebView mWebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebView = new HTML5WebView(this);
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
} else {
// mWebView.loadUrl("http://player.vimeo.com/video/27244727");
mWebView.loadUrl("http://player.vimeo.com/video/81995018");
}
setContentView(mWebView.getLayout());
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
public void onStop() {
super.onStop();
mWebView.stopLoading();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (mWebView.inCustomView()) {
mWebView.hideCustomView();
// mWebView.goBack();
//mWebView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
package com.example.newsolution;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
public class HTML5WebView extends WebView {
private Context mContext;
private MyWebChromeClient mWebChromeClient;
private View mCustomView;
private FrameLayout mCustomViewContainer;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
private FrameLayout mContentView;
private FrameLayout mBrowserFrameLayout;
private FrameLayout mLayout;
static final String LOGTAG = "HTML5WebView";
private void init(Context context) {
mContext = context;
Activity a = (Activity) mContext;
mLayout = new FrameLayout(context);
mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(a).inflate(R.layout.custom_screen, null);
mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(R.id.main_content);
mCustomViewContainer = (FrameLayout) mBrowserFrameLayout.findViewById(R.id.fullscreen_custom_content);
mLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
// Configure the webview
WebSettings s = getSettings();
s.setBuiltInZoomControls(true);
s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
s.setUseWideViewPort(true);
s.setLoadWithOverviewMode(true);
// s.setSavePassword(true);
s.setSaveFormData(true);
s.setJavaScriptEnabled(true);
mWebChromeClient = new MyWebChromeClient();
setWebChromeClient(mWebChromeClient);
setWebViewClient(new WebViewClient());
setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
// enable navigator.geolocation
// s.setGeolocationEnabled(true);
// s.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");
// enable Web Storage: localStorage, sessionStorage
s.setDomStorageEnabled(true);
mContentView.addView(this);
}
public HTML5WebView(Context context) {
super(context);
init(context);
}
public HTML5WebView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public HTML5WebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public FrameLayout getLayout() {
return mLayout;
}
public boolean inCustomView() {
return (mCustomView != null);
}
public void hideCustomView() {
mWebChromeClient.onHideCustomView();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if ((mCustomView == null) && canGoBack()){
goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private class MyWebChromeClient extends WebChromeClient {
private Bitmap mDefaultVideoPoster;
private View mVideoProgressView;
#Override
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
{
//Log.i(LOGTAG, "here in on ShowCustomView");
HTML5WebView.this.setVisibility(View.GONE);
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mCustomViewContainer.addView(view);
mCustomView = view;
mCustomViewCallback = callback;
mCustomViewContainer.setVisibility(View.VISIBLE);
}
#Override
public void onHideCustomView() {
System.out.println("customview hideeeeeeeeeeeeeeeeeeeeeeeeeee");
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();
HTML5WebView.this.setVisibility(View.VISIBLE);
HTML5WebView.this.goBack();
//Log.i(LOGTAG, "set it to webVew");
}
#Override
public View getVideoLoadingProgressView() {
//Log.i(LOGTAG, "here in on getVideoLoadingPregressView");
if (mVideoProgressView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
}
return mVideoProgressView;
}
#Override
public void onReceivedTitle(WebView view, String title) {
((Activity) mContext).setTitle(title);
}
#Override
public void onProgressChanged(WebView view, int newProgress) {
((Activity) mContext).getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress*100);
}
#Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
}
static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
Details is here

Web View Fragment html embeed video fullscreen suport

Hello everyone i got a question regarding how to enable full screen support in html embed videos on my webview i have hardware accelerated true on manifest and the video works ok but wen pressed to go fullscreen the video stops.
here is my code
import com.photoshop.video.tutorials.R;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class WebViewFragment extends Fragment {
public final static String TAG = WebViewFragment.class.getSimpleName();
private WebView viewContentWebView;
private String url;
private boolean resetHistory = true;
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.webview, container, false);
final ProgressBar viewContentProgress = (ProgressBar) v.findViewById(R.id.progress);
viewContentWebView = (WebView) v.findViewById(R.id.webview);
viewContentWebView.getSettings().setJavaScriptEnabled(true);
viewContentWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
viewContentWebView.loadUrl("file:///android_asset/myerrorpage.html");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
});
viewContentWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
viewContentProgress.setProgress(newProgress);
viewContentProgress.setVisibility(newProgress == 100 ? View.GONE : View.VISIBLE);
if (newProgress == 100 && resetHistory) {
viewContentWebView.clearHistory();
resetHistory = false;
}
}
});
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
reload();
}
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden)
viewContentWebView.stopLoading();
else
reload();
}
public void setUrl(String url) {
this.url = url;
if (viewContentWebView != null)
viewContentWebView.stopLoading();
resetHistory = true;
}
public void reload() {
if (TextUtils.isEmpty(url))
return;
viewContentWebView.loadUrl(url);
}
public boolean onBackPressed() {
if (viewContentWebView.canGoBack()) {
viewContentWebView.goBack();
return true;
}
return false;
}
}
How can i achieve this
many thanks in advance and a little patience with me because i am very very VERY new to android
You should override the two following methods in your WebChromeClient:
public void onShowCustomView(View view, CustomViewCallback callback);
public void onHideCustomView();
This is an extract of the code I'm using:
private View mCustomView;
private class MyWebChromeClient extends WebChromeClient {
private int mOriginalOrientation;
private FullscreenHolder mFullscreenContainer;
private CustomViewCallback mCustomViewCollback;
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mOriginalOrientation = mActivity.getRequestedOrientation();
FrameLayout decor = (FrameLayout) mActivity.getWindow().getDecorView();
mFullscreenContainer = new FullscreenHolder(mActivity);
mFullscreenContainer.addView(view, ViewGroup.LayoutParams.MATCH_PARENT);
decor.addView(mFullscreenContainer, ViewGroup.LayoutParams.MATCH_PARENT);
mCustomView = view;
mCustomViewCollback = callback;
mActivity.setRequestedOrientation(mOriginalOrientation);
}
#Override
public void onHideCustomView() {
if (mCustomView == null) {
return;
}
FrameLayout decor = (FrameLayout) mActivity.getWindow().getDecorView();
decor.removeView(mFullscreenContainer);
mFullscreenContainer = null;
mCustomView = null;
mCustomViewCollback.onCustomViewHidden();
// show the content view.
mActivity.setRequestedOrientation(mOriginalOrientation);
}
static class FullscreenHolder extends FrameLayout {
public FullscreenHolder(Context ctx) {
super(ctx);
setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
}
#Override
public boolean onTouchEvent(MotionEvent evt) {
return true;
}
}

Categories

Resources