WebView's onPause() not Working - android

I have WebView inside an activity that extends AppCompatActivity, I'm trying to stop Audio playback inside webview when the Activity is closed/swapped but it's not working, the sound keeps playing all the time, below in my code
public class PostDetailsActivity extends AppCompatActivity{
WebView mArticleText;
...
void loadDatatoWebView(String html){
String base64 = Base64.encodeToString(html.getBytes(), Base64.DEFAULT);
mArticleText.loadData(base64, "text/html; charset=utf-8", "base64");
mArticleText.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null) {
// open links in external browser
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {
return false;
}
}
});
}
#Override
protected void onPause() {
super.onPause();
mArticleText.pauseTimers();
mArticleText.onPause();
}
#Override
protected void onResume() {
super.onResume();
mArticleText.onResume();
}
}
I tried adding WebView.loadUrl("about:blank")and it solved the playback problem but introduced some UX problems, the webview had to load again when the activity is resumed ant causes an annoying delay as rendering could take some time.

Related

App stops when calling Webview back to Activity Intent

I developed a simple app that has two activities. When I call Menu activity to Webview using intent, it opens very well in web view, but when I click the button to return back to Activity, it crashes and asks to "close the app." Below is my java and it looks fine without errors. The log cat as well doesn't display any errors.
Who has the solution to these?
public class WebView extends AppCompatActivity {
WebView webView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
String url = getIntent().getStringExtra("site_url");
android.webkit.WebView webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setSupportZoom(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("" + url);
}
private class MywebClient extends WebViewClient {
#Override
public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
}
#Override
public void onBackPressed() {
android.webkit.WebView webView = null;
if(webView.isFocused() && webView.canGoBack())
{
webView.goBack();
}else{
super.onBackPressed();
}
}
}
Your problem is right here, in onBackPressed():
android.webkit.WebView webView = null;
if(webView.isFocused() && webView.canGoBack())
You set the variable webView to null and then you call a method isFocused() on it. That will cause a NullPointerException.
Change this to:
android.webkit.WebView webView = findViewById(R.id.webView);
if(webView.isFocused() && webView.canGoBack())

How to get Webview hyperlink to open in webview app instead of browser

I am trying to build a Webview app using android studio and I am currently having a problem. The index page shows perfectly on the app but whenever i click a hyperlink it redirects me to the browser and then to the website how can I get it to redirect me to another page whilst in the app built from webview. Here is a snippet of the main activity java
public class MainActivity extends AppCompatActivity {
private WebView mywebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mywebView = (WebView) findViewById(R.id.webview);
WebSettings websettings=mywebView.getSettings();
mywebView.loadUrl("https://www.cavaapperal.co.za/");
websettings.setJavaScriptEnabled(true);
}
public class myWebClient extends WebViewClient{
#Override
public void onPageStarted (WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed (){
if (mywebView.canGoBack()) {
mywebView.goBack();
} else{
super.onBackPressed();
}
}
}
webView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {
return false;
}
}
});
WebView link click open default browser
Kindly see the following link

Code Music Streaming in Background with Android App

I have built a website that streams mp3 playlists using javascript and created an android app that uses WebView to embed the site. Unfortunately the music stops when the phone sleeps. Is it possible to code the app to maintain the javascript executing to keep music playing while running in background? I would like it to function similar to Pandora as an example but not sure if this is possible using WebView.
try this, i test this code so keep music playing while running in background, maybe help you:
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView)findViewById(R.id.webview);
// Enable javascript
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
final Uri uri = Uri.parse(url);
return customUriHanlder(uri);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
final Uri uri = request.getUrl();
return customUriHanlder(uri);
}
private boolean customUriHanlder(final Uri uri) {
Log.i("TAG", "Uri =" + uri);
final String host = uri.getHost();
final String scheme = uri.getScheme();
// you can set your specific condition
if (true) {
// Returning false means that you are going to load this url in the webView itself
return false;
} else {
// Returning true means that you need to handle what to do with the url
// open web page in a Browser
final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
return true;
}
}
});
// Load the webpage
webView.loadUrl("https://google.com/");
}
#Override
public void onPause() {
super.onPause();
webView.onResume();
}
#Override
public void onResume() {
super.onResume();
webView.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
webView.onResume();
}

Android WebView issue on override url loading

I’m trying to override url loading when clicking on a link on an app WebView.
The page loads but the WebView will keep it’s last scroll position and content size.
Is there some parameter I forgot to set on the WebView to reset the content size and the scroll position on next load?
Here’s how I’m using it:
#SuppressLint("SetJavaScriptEnabled")
#AfterViews
protected void afterViews() {
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebClient());
webView.setWebChromeClient(new ChromeClient());
webView.loadUrl(url);
}
public class WebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean isValidEmail = url.startsWith("mailto:") && Patterns.EMAIL_ADDRESS.matcher(url.substring("mailto:".length())).matches();
boolean isValidPhone = url.startsWith("tel:") && Patterns.PHONE.matcher(url.substring("tel:".length())).matches();
if (url.startsWith("about:")) {
return super.shouldOverrideUrlLoading(view, url);
}
if (isValidEmail) {
Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
startActivity(Intent.createChooser(sendIntent, ""));
} else {
if (isValidPhone) {
Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(Intent.createChooser(dialIntent, ""));
} else {
WebViewActivity.this.setPageTitle(url);
webView.loadUrl(url);
}
}
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
//..
}
}
public class ChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int progress) {
//...
}
}
Thanks.
Did you try to set scroll position in onPageFinished?
#Override
public void onPageFinished(WebView view, String url) {
// other code...
view.scrollTo(0,0);
}
That should set WebView content back to top, and not on old scroll position
Edit 1:
Sometimes if the page loads for a long time this won't work properly, so we must wait for page to get fully loaded:
#Override
public void onPageFinished(WebView view, String url) {
view.postDelayed(new Runnable() {
#Override
public void run() {
webView.scrollTo(0, 0);
}
// Delay the scrollTo to make it work
}, 300);
}
Please note that webView this time is not the WebView from the method onPageFinished, but the WebView fetched from the layout (same one as in afterViews() method).
#Bojan Kopanja, my sincere apologies for misleading.
It turns out I had the webview inside a pull to refresh listener with a scrollview and removing that got rid of the problem.
Thanks for your help nevertheless.

Launching new activity resets ViewPager

I have a ViewPager with each view being a WebView. In the Actionbar I have a menu item, where the user can open the web page in their default browser using this code:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mUrl)));
However, if a user clicks on a link in the WebView, then opens the site in their default browser, then goes back to my app, they are shown the original web page, not the page they clicked to. I thought about using startActivityForResult instead of startActivity, but that would only work if I opened a new activity in my own app, right?
This is the code for my ViewPager:
Fragment
public class Browser extends SherlockFragment {
private String mUrl;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
activity = getActivity();
setHasOptionsMenu(true);
mUrl = GetUrl();
mWebView = (WebView)getView().findViewById(R.id.webview);
mWebView.loadUrl(mUrl);
mWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(final MenuItem item)
{
if (item.getItemId() == R.id.open) {
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mUrl)));
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
}
Activity
public class BrowserPager extends SherlockFragmentActivity implements Interfaces.OnBrowserSetTitle {
#Override
public void onCreate(final Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.browser_pager);
}
}
Nevermind, I'm an idiot. I was resetting the ViewPager in onResume of the Activity, which was causing the webpage to reset. Moving the code to reset the ViewPager to onCreate fixed my issue.

Categories

Resources