Pausing & Resuming Java Script Execution in Web View PRO

When executing code written in Java Script in our web view we would like to pause it when the user moves to another activity and resumes it when he returns. The following code sample includes two activities. The first activity includes a web view that executes code written in Java Script. The second activity is a very simple activity I chose to add in order to simulate moving from one activity to another and returning back.

The following is the source code of the first activity. As you can see, the activity includes code for pausing and resuming the java script execution in according with its life cycle.

package com.abelski.samples;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.support.v4.app.NavUtils;

public class HybridActivity extends Activity
{
	private WebView web;
	
	@Override
	public void onPause()
	{
		super.onPause();
		web.getSettings().setJavaScriptEnabled(false);
	}	
	
	@Override
	public void onResume()
	{
		super.onResume();
		web.getSettings().setJavaScriptEnabled(true);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_hybrid);
		web = (WebView) findViewById(R.id.webView1);
		//web.getSettings().setJavaScriptEnabled(true);
		web.loadUrl("file:///android_asset/www/index.html");
		web.addJavascriptInterface(new Logic(), "ob");
		Button bt = (Button) findViewById(R.id.button1);
		bt.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(HybridActivity.this,
						com.abelski.samples.AnotherActivity.class);
				startActivity(intent);
			}
		});

	}

	public class Logic
	{
		public void writeToLog(String tag,String str)
		{
			Log.i(tag,str);
		}
	}

}

The following is the html code that includes few lines in Java Script the web view renders to the screen.

<script type="text/javascript">
index = 1;
setInterval(function(){writeLog();},1000);
function writeLog()
{
	var msg = "within writeLog function... index="+index;
	window.ob.writeToLog("js",msg);
	document.getElementById("msg").innerHTML = msg;
	index++;
}
</script>
<div id="msg">...</div>

The following is the source code of the simple second activity. It is a simple activity I added just to simplify the demonstration.

package com.abelski.samples;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class AnotherActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView text = new TextView(this);
        text.setText("another activity");
        text.setTextSize(20);
        this.setContentView(text);
    }
}

The following is the manifest file that configures our application. It informs the android platform about the two activities we developed.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.abelski.samples"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".HybridActivity"
            android:label="@string/title_activity_hybrid" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
                <activity
            android:name=".AnotherActivity"
            android:label="@string/title_activity_hybrid" >
        </activity>
    </application>
</manifest>

The following is a short video clip that shows the execution of this code sample and explains it.

You can download the project code and find more information in my free Android Fundamentals course at www.abelski.org.

Share:

The Visitor Design Pattern

The Visitor Design Pattern

The visitor design pattern allows us to add operations to objects that already exist without modifying their classes and without extending them.

What are Anti Patterns?

Anti Patterns

Unlike design patterns, anti patterns just seem to be a solution. However, they are not a solution and they cause additional costs.

Virtual Threads in Java Professional Seminar

Virtual Threads in Java

The use of virtual threads can assist us with improving the performance of our code. Learn how to use virtual threads effectively.

NoSQL Databases Courses, Seminars, Consulting, and Development

MongoDB Design Patterns Meetup

The use of MongoDB involves with various cases in which we can overcome performance issues by implementing specific design patterns.

image of woman and database

Record Classes in Java

Learn how to define record classes in Java, and when to use record classes in your code. Stay up to date with the new Java features.

Accessibility | Career | Conferences | Design Patterns | JavaScript | Meetups | PHP | Podcasts | Python | Self Learning

Teaching Methodologies | Fullstack | C++ | C# | CSS | Node.js | Angular | Java | Go | Android | Kotlin | Swift | Academy

Front End Development | Scala | Architectures | Cloud | Big Data | Internet of Things | Kids Learn Programming

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Skip to content Update cookies preferences