The most frequently asked questions in Android interviews are here. Most of the questions were collected from the Internet, and the blogger made a great effort to sort out and summarize. There are inevitably some shortcomings, please forgive me. This blog belongs to Androi, enough of you!! The other articles will be published in succession, the first time will be published on my Github, please pay attention to. This blog consists of five sections: Hot Spots, Basics, Advanced, Performance Optimization, and Advanced. The follow-up will continue to supplement and improve, I hope to increase the confidence for small partners to find a job 😄.

hot

How can Service not be killed

The Android process is deathless in three ways:

  • A. Provide process priority to reduce the probability of process killing. Method 1: Monitor the lock screen unlock event of the mobile phone, start an Activity with 1 pixel when the screen is locked, and destroy the Activity when the user unlocks the screen. Method 2: Start the foreground service. Method 3: Improve the service priority: In the androidmanifest.xml file, you can set the highest priority for intent-filter by android:priority = “1000”. 1000 is the highest value. If the number is smaller, the priority is lower.
  • B. After the process is killed, activate it in method 1: register a high-frequency broadcast receiver to awaken the process. For example, the network changes, unlock the screen, boot, etc. Method 2: The two processes evoke each other. Method three: rely on system arousal. Method 4: Restart service: service +broadcast in onDestroy. When a service goes through ondeStory, it sends a customized broadcast. When the service receives an ondeStory, it restarts the service.
  • C. Rely on a third party to access Xiaomi Push on Xiaomi mobile phones (including MIUI) and Huawei mobile phones to access Huawei Push according to different terminals; Other mobile phones can consider access to Tencent carrier pigeon or Aurora push and Xiaomi push to do A/B Test.

See blog: Android process to keep alive tips

ButterKnife has little impact on performance because instead of using reflection, ButterKnife uses the Annotation Processing Tool(APT), an Annotation processor, a javAC Tool for scanning and parsing Java annotations at compile time. Executed at compile time, it works by reading Java source code, parsing annotations, and generating new Java code. The newly generated Java code is eventually compiled into Java bytecode, and the annotation parser cannot change the Java classes read in, such as adding or deleting Java methods.

A brief analysis of Java Annotation and several common open source project Annotation principles of ButterKnife simple principle implementation

basis

What are the Activity and Fragment life cycles?




Screenshot 2016-09-19 PM 8.10.27.png

The Activity life cycle when switching between horizontal and vertical screens

Android :configChanges= “Orientation” When you do not set the Activity’s Android :configChanges= “Orientation” when you set the Activity’s Android :configChanges= “Orientation” when you set the Activity’s Android :configChanges= “orientation” when you set the Activity’s Android :configChanges= “orientation” Cut screen will still call each life cycle, somehow the screen will only perform a switch Settings Activity of the android: configChanges = “orientation” | “keyboardHidden, cut the screen each life cycle will not call again, Only the onConfigurationChanged method is executed

AsyncTask’s thread pool, ThreadPoolExecutor, is shared within the process scope and is static, so AsyncTask controls all subclass instances within the process scope. Because of this limitation, when using the default thread pool, if the number of threads exceeds the maximum capacity of the thread pool, the thread pool will burst (this problem does not occur after 3.0, which defaults to serial execution). In this case, you can try to customize the thread pool to work with asyncTask.

About the default thread pool: the core thread pool has a maximum of CPU_COUNT+1, and a maximum of CPU_COUNT*2+1. The maximum number of waits in the thread queue is 128, but the thread pool can be customized. Thread pools are managed by asyncTasks. Thread pools allow tasks to run in parallel. Note that data consistency can be overwritten by old data in concurrent cases, such as volatile variables. So if you want tasks to run serially, use SERIAL_EXECUTOR.

Differences between AsyncTask in different SDK versions: When AsyncTask was first introduced, asynchronous tasks were executed sequentially in an independent thread, that is, only one task could be executed at a time, not in parallel. From 1.6, the excute method of AsyncTask cannot execute programs immediately. AsyncTask introduces a thread pool that supports the execution of up to five asynchronous tasks at a time. This means that only five threads can run at a time, and the remaining threads must wait until one of the preceding threads has finished. In other words, if there are more than five AsyncTask instances in a process, then if the first five are running for a long time, the sixth one will have to wait. This is a limitation of AsyncTask and is not fixed prior to 2.3. If your application requires a large number of background threads to perform tasks, you may have to abandon AsyncTask and create your own Thread pool to manage threads. It has to be said that while AsyncTask is easier to use than Thread, it can only run up to five threads at a time, which greatly limits its power. You have to carefully design your application, stagging AsyncTask time, trying to be divided, or making sure that the number of asyncTasks is not more than five. Otherwise you’re going to run into the problem that I mentioned last time. Perhaps Google has realized the limitations of AsyncTask and has made some changes to the AsyncTask API since Android3.0: only one thread is started to perform one task at a time, and then the second task is executed after completion, which means that there is only one background thread executing the submitted task.

  • Many developers assume that an AsyncTask created in an Activity will be destroyed when the Activity is destroyed. However, this is not the case. The AsyncTask executes until the doInBackground() method completes. Then, if cancel(Boolean) is called, the onCancelled(Result Result) method is executed; Otherwise, the onPostExecute(Result Result) method is executed. If the AsyncTask is not canceled before the Activity is destroyed, it may cause the AsyncTask to crash. Because the view it wants to process is no longer there. So, we always have to make sure that the task is canceled before the destruction activity. In short, we use AsyncTask to ensure that the AsyncTask is cancelled correctly.
  • 2. Memory leak If an AsyncTask is declared as a non-static inner class of an Activity, then the AsyncTask retains a reference to the Activity. If the Activity has been destroyed and the background AsyncTask thread is still executing, it will continue to hold the reference in memory, causing the Activity to be unable to be reclaimed and causing a memory leak.
  • 3. As a result, missing screen rotation or the Activity being killed by the system in the background will cause the Activity to be recreated. The previously running AsyncTask will hold a reference to the previous Activity that is invalid. Calling onPostExecute() to update the interface will no longer work.
  • Before Android1.6, AsyncTask was serial, in 1.6 to 2.3, it was parallel. Since 2.3, it has been modified to support both parallel and serial execution, executing the execute() method directly when serial execution is desired, and executeOnExecutor(Executor) if necessary.

Acitivty’s task stack

Use the android: launchMode = “standard | singleInstance | single Task | singleTop” to control the Acivity Task stack.

The task stack is a lifO structure. The activities at the top of the stack are in focus, and when the back button is pressed, the activities in the stack are ejected one by one and their onDestory() method is called. If there is no Activity in the stack, the system will reclaim the stack. By default, each APP has only one stack, named after the package name of the APP.

  • Standard: In standard mode, each time an Activity is started, a new instance of the Activity is created and pushed to the top of the task stack, regardless of whether the Activity already exists. All three callbacks to the Activity start (onCreate()->onStart()->onResume()) are executed.
  • SingleTop: Top of stack reuse mode. In this mode, if the new Activity is already at the top of the task stack, the Activity is not recreated, so its launch triple callback is not executed, and the Activity’s onNewIntent() method is called back. If the Activity already exists but is not on the top of the stack, then it applies to Standard mode as well.
  • SingleTask: In-stack reuse mode. When creating such an Activity, the system first confirms that the required task stack has been created, or otherwise creates the task stack first. If there is already an instance of an Activity in the stack, the Activity is moved to the top of the stack,onNewIntent(), and singleTask clears all activities on top of the current Activity.(Clear Top)
  • singleInstance : Enhanced singleTask mode, in which an Activity can only reside in a singleTask stack. Due to the nature of in-stack reuse, subsequent requests do not create new activities unless the unique task stack is destroyed by the system The Activity stack is managed in units of ActivityRecords, all of which are placed in a List. You can think of an ActivityRecord as an Activity stack

OnSaveInstanceState () and onRestoreIntanceState() are not used when a user or programmer actively destroys an Activity, but are otherwise invoked to save interface information. This will not be used if the user presses back or finish () in the code.

What is the priority of a process in Android?

  • Foreground process: the Activity that is interacting with the user or the Service that the Activity uses. The foreground process is the last to be killed if the system runs out of memory
  • Visible process: This can be an onPause Activity or a Service bound to it that is visible to the user but cannot interact with the user because it has lost focus
  • Service process: it runs the Service started by the startService method. Although it is not visible to the user, it is concerned by the user. For example, the user is listening to the music in the non-music interface or downloading the file on the non-download page. It is terminated when the system needs space to run the first two processes
  • Background process: which runs the onStop method and stop the program, but is not the user’s current concern, such as QQ hanging in the background, such process system once there is no memory will be the first to be killed
  • Empty process: a process that does not contain any of the application’s components. Such a process system would not normally allow it to exist

Serializable and Parcelable serialize, which means converting an object to a storeable or transportable state. Serialized objects can be transferred over the network or stored locally.

  • Serializable (Java built-in) : Serializable stands for serialization, which means converting an object to a state that can be stored or transferred. Serialized objects can be transferred over the network or stored locally.
  • Parcelable (Android only) : In addition to Serializable, the same effect can be achieved with Parcelable. Instead of serializing an object, Parcelable splits the entire object into the data type supported by the Intent. This also realizes the function of passing objects.
  • Tween animation. By specifying the View at the beginning and end of the state and change time, way, the content of the View to complete a series of graphic transformation to achieve animation effect. Alpha, Scale,Translate, Rotate.
  • AnimationDrawable controls the animation-List XML layout
  • Introduced in PropertyAnimation 3.0, the core idea of PropertyAnimation is the change of value.

A Property Animation has two steps: 1. Calculate property values 2. Set property values for the properties of the target object, that is, apply and refresh animations




valuecaculate.png

The calculation of attributes is divided into three processes:

  • To execute an animation, you need to create a ValueAnimator and specify the start and end values and duration of the target object properties. During the entire animation process after the start call, ValueAnimator calculates a score between 0 and 1, representing the percentage of completed animations for the animation, based on the animation time that has been completed. 0 means 0% and 1 means 100%.
  • Process 2: Interpolated Fraction When ValueAnimator has interpolated a finished animation fraction, it will invoke the currently interpolated timeator to compute a interpolated fraction. During the calculation, the percentage of completed animation is added to the new interpolation calculation.
  • When the interpolation score is calculated, ValueAnimator calls the appropriate TypeEvaluator based on the interpolation score to evaluate the property values in the motion. The above analysis introduces two concepts: Elapsed fraction and interpolated fraction.

Android data storage form

  • SQLite: SQLite is a lightweight database that supports basic SQL syntax and is often used as a data storage method. Android provides a class called SQLiteDatabase for this database, which encapsulates some apis for manipulating the database
  • SharedPreference: Stored as key-value pairs. It is essentially an XML file, often used to store simple parameter Settings.
  • File: I/O storage method, commonly used to store large amounts of data, but the disadvantage is that updating the data can be difficult.
  • ContentProvider: A data storage method shared by all applications in the Android operating system. Data is usually private between applications, so this storage method is rarely used, but it is an essential storage method. For example, audio, video, pictures and address books can be stored in this way. Each Content Provider provides a public URI (wrapped as a URI object). If your application has data to share, you need to define a URI for that data using the Content Provider. Other applications then pass in this URI through the Content Provider to manipulate the data.

The Context related

The Context of an Activity is different from that of a Service or Application. The Activity inherits the ContextThemeWraper. The others inherit from ContextWrapper. Each Activity and Service and Application Context is a new ContextImpl object getApplication() that gets the Application instance. But this method can only be called in activities and services. If you want to get an instance of an Application in a BroadcastReceiver, you might want to use it in an Activity or a Service for the most part. You can use the getApplicationContext() method, which has a wider scope than getApplication(). Any instance of a Context, We can get our Application object by calling the getApplicationContext() method. Instead of using the Application context to create the Toast and dialog, only the Activity context can be used. The number of contexts is equal to the number of activities + the number of services + 1, which is Application

New features in Android5.0

  • MaterialDesign design style
  • Support for multiple devices
  • Supports 64-bit ART VMS

Android6.0 new features

  • Lots of nice, smooth animations
  • Support quick charging switch
  • Support folder drag and drop applications
  • Added professional mode to camera

Android7.0 new features

Json

  • All the way through JSON is JavaScript Object Notation, which is JavaScript Object Notation
  • JSON is a syntax for storing and exchanging text information, similar to XML but smaller, faster, and easier to parse than XML
  • JSON is a lightweight text data interchange format that is language independent, self-descriptive, and easy to understand

An object can contain multiple name/value pairs, such as:

{"name":"zhangsan" , "age":25}Copy the code

Introduce dependencies in Android Studio using Google’s GSON package for parsing:

The compile 'com. Google. Code. Gson: gson: 2.7'Copy the code

It is important to note that the variable name in the entity class must be the same as the value name in json. Json1 parsing Our entity class here is student.class

Gson gson = new Gson();
Student student = gson.fromJson(json1, Student.class);Copy the code

Json2 can be parsed as an int array or as an Integer List. Parse to an array:

Gson gson = new Gson(); int[] ages = gson.fromJson(json2, int[].class); List: Gson Gson = new Gson(); List ages = gson.fromJson(json2, new TypeToken>(){}.getType);Copy the code

Json3 can also be parsed as a List or an array, so we’ll go straight to a List.

Gson gson = new Gson();
List students = gson.fromJson(json3, new TypeToke>(){}.getType);Copy the code

What classes are available for parsing XML on Android, and which are officially recommended? And how they work and how they differ

  • The DOM parsing

    Advantages: 1.XML trees are completely stored in memory, so you can modify their data and structure directly. 2. You can use this parser to access any node in the XML tree at any time.3. The DOM parser API is also relatively simple to use. Disadvantages: Reading XML documents into memory can be very resource-intensive if they are large. Usage scenarios :DOM is the official W3C standard for representing XML documents in a platform – and language-independent manner. The DOM is a collection of nodes organized in a hierarchy. This hierarchy allows developers to find specific information in the tree. Analyzing the structure usually requires loading the entire document and constructing a hierarchy before any work can be done. DOM is based on an object hierarchy.

  • SAX parsing

    Advantages: SAX is less memory intensive because it lets the developer decide which tags to process. SAX’s extensibility is especially good when the developer only needs to work with part of the data contained in the document. Disadvantages: XML parsing in SAX requires sequential execution, making it difficult to access different data in the same document. In addition, the parsing and coding process based on this method is also relatively complicated. Usage scenario: This method is very effective when there is a large amount of data in a document without traversing or analyzing all the data. Instead of reading the entire document into memory, the method simply reads the document label required by the program.

  • Xmlpull parsing

    The Android SDK provides the XMLPull API, which, like SAX, manipulates a file based on a stream and then calls back a handler written by the developer based on node events. Because of stream-based processing, XMLPull and SAX are less memory-intensive than DOM, where all nodes are presented in memory as oak trees; xmlPull is more concise than SAX, and it does not require scanning the entire stream.

The difference between Jar and Aar

The Jar contains only code, and the AAR contains not only code but also resource files, such as drawable files and XML resource files. For Android libraries that don’t change very often, we can refer directly to an AAR to speed up compilation

What is tertiary caching

  • Network loading is not prioritized, which is slow and wastes traffic
  • Local cache, secondary priority loading, fast
  • Memory cache, priority loading, fastest

Principle of Three-level caching

When you first load an Android App, you definitely need to get an image through network interaction, and then you can save the image to your local SD card and memory and then when you run the App, you have priority access to the image cache in memory, and if it’s not in memory, you load the image from your local SD card so anyway, only when you first access something new, Only through the Internet access to picture resources

How much memory does Android allocate for each application? Android applications are generally limited to 16MB of memory, but some have 24MB

RunOnUiThread (Runnable) view.post (Runnable), view.postDelay (Runnable,long) Handler AsyncTask

The advanced

A condition causing a memory leak

  • For resources that use BraodcastReceiver, ContentObserver, File, Cursor, Stream, Bitmap, etc., you should shut down or log out when your Activity is destroyed.
  • Static inner classes hold external member variables (or context) : you can use weak references or use ApplicationContext.
  • Inner classes hold external class references, and in asynchronous tasks, external member variables.
  • Objects in the collection that are not useful are not removed in time.
  • Recycle () is used after using Bitmap and null is assigned.
  • A message in a MessageQueue will leak memory if it is not processed by the activity when it is destroyed. This can be resolved using weak references.
  • When the Adapter was constructed, no cached convertView was used.
  • If a listener is not used, remove it in time. Remove, Destroy, Destroy Remove is required in Destroy, especially if it starts with addListener.
  • Activity leaks can be done using LeakCanary.

Android Memory Overflow Solution (OOM

  • Do some processing on memory references, commonly used soft references, weak references
  • Image loading in memory is done directly in memory, such as edge compression
  • Dynamically reclaim memory
  • Optimize heap memory allocation for Dalvik VIRTUAL machine
  • Customize heap memory size

Fragment/Activity/Window/View

An Activity is like a craftsman (a control unit), a Window is like a Window (a carrying model), a View is like a Window splint (a display View), layoutInflaters are like scissors, and Xml configurations are like a Window splint.

We call Attach in our Activity, we create a Window and that Window is a subclass of PhoneWindow, Create PhoneWindow in attach and call setContentView(r.layout.xxx) in the Activity which is actually called getWindow().setContentView() Call the setContentView method in PhoneWindow to create ParentView: 
 as a subclass of ViewGroup, What is actually created is a DecorView(a subclass of FramLayout) that populates the specified r.layout. XXX 
 with a layout filler call to the ViewGroup Call removeAllView() of the ViewGroup, remove all the views and add a new view: addView()

Fragments can be used as part of the Activity interface. You can have multiple fragments in an Activity at the same time, and a Fragment can be used in multiple activities. You can add, remove, or replace fragments while an Activity is running. Fragments can respond to their own input events and have their own life cycles, which are influenced by the life cycle of the host Activity.

The difference between the JVM and the Dalvik Virtual Machine

  • JVM:.java -> javac ->.class -> jar ->.jar architecture: heap and stack architecture.
  • DVM:.java -> javac ->.class -> dx.bat ->.dex architecture: register (a cache on the CPU)

How to consider the security of data transmission If the application does not have any security measures for data transmission, the attacker sets up a phishing network to change the DNS server. This server can retrieve user information or act as a middleman to exchange data with the original server. In SSL/TLS communication, the client uses the digital certificate to determine whether the server is trusted, and uses the public key of the certificate to encrypt communication with the server.

Custom View related methods 1. Custom properties 2. OnLayout (Viewgroup) 3. Interaction: onIntercepterTouchEvent() onTouchEvent()

When a finger touches the screen, the system calls the corresponding View’s onTouchEvent and passes in a series of actions.

DispatchTouchEvent is executed in the following order:

First fire the ACTIVITY’s dispatchTouchEvent, then fire the ACTIVITY’s onInterceptTouchEvent. Then the dispatchTouchEvent for LAYOUT is fired, and the onInterceptTouchEvent for LAYOUT is fired. This explains why you must call super.DispatchTouchEvent () when overriding a ViewGroup;

(1)dispatchTouchEvent:

This method is typically used for initial handling of events, since the action is dispatched from there, super.DispatchTouchEvent is usually called. OnInterceptTouchEvent will continue to be called, and the onInterceptTouchEvent will determine the event flow.

(2)onInterceptTouchEvent:

An event that returns true is passed to its own onTouchEvent(); If false is returned, dispatchTouchEvent() is passed to the next View;

(3)onTouchEvent():

If the return value is true, the event is consumed by itself, and subsequent actions are processed by it. If it returns false, it will not consume the event itself, and will go up and let the onTouchEvent of the other parent View be processed

Pseudo-code for the three method relationships: if the current View intercepts the event, it hands it to its onTouchEvent, otherwise it throws it to its child View to continue the same process.

public boolean dispatchTouchEvent(MotionEvent ev)
{
    boolean consume = false;
    if(onInterceptTouchEvent(ev))
    {
        consume = onTouchEvent(ev);
    }
    else
    {
        consume = child.dispatchTouchEvent(ev);
    }
    return consume;
}Copy the code

Passing of onTouchEvent:

When there are multiple levels of View, the action will be passed until the deepest View is encountered, if the parent level allows. So the touch event first calls the onTouchEvent of the lowest level View. If the onTouchEvent of the View receives a touch action and does the corresponding processing, there are two final return methods: return true and Return false. Return true will tell the system that the current View needs to handle the touch event. ACTION_MOVE and ACTION_UP sent by the system in the future still need to listen and receive, and the action this time has been processed. It is not possible for a parent View to trigger an onTouchEvent. So each action can have at most one onTouchEvent that returns true. If false is returned, the system will be notified that the current View does not care about the touch event, and the action will be propagated to the parent, calling the parent View’s onTouchEvent. However, the View will not accept any action after the touch event, and the onTouchEvent will not be triggered in the touch event, which means that once the View returns false, ACTION_MOVE,ACTION_UP and other subsequent actions will not be passed in the View, but the next touch ACTION will still be passed in.

The parent layer onInterceptTouchEvent

As mentioned earlier, the underlying View can receive this event only if the parent allows it. Assuming that the dispatch method of the parent level is not changed, the onInterceptTouchEvent method of the parent View will be called before the system calls the underlying onTouchEvent to determine whether the parent View will intercept the action after the touch event. If the onInterceptTouchEvent returns true, all actions that follow the touch event will be passed to the parent View’s onTouchEvent. Subsequent actions do not need to ask onInterceptTouchEvent. OnInterceptTouchEvent will not be called when an action is issued after the touch event until the next touch event. If onInterceptTouchEvent returns false, this action will be sent to the deeper View, and each subsequent action will ask the parent onInterceptTouchEvent if it needs to intercept the touch event. Only the ViewGroup has onInterceptTouchEvent method, because a normal View must be the deepest one, and the touch will call onTouchEvent() from the View.

The underlying View getParent (). RequestDisallowInterceptTouchEvent (true)

For the underlying View, there is a way to stop the parent View to get touch events, is to call getParent () requestDisallowInterceptTouchEvent (true) method. Once the bottom View calls the action from touch, the parent View will no longer call onInterceptTouchEvent, nor will it be able to intercept future actions. (If the parent ViewGroup and the bottom View need to intercept different actions, Or different gestures for touch, cannot use this to write dead).

ART and Dalvik

Applications on ART are quick to start and run, but they consume more storage space and take longer to install. In general, the effect of ART is “space for time”.

ART: Ahead of Time

Dalvik: Just in Time

What is Dalvik? Dalvik is a Java virtual machine designed by Google for the Android platform. Dalvik VIRTUAL machine is one of the core components of Android mobile device platform jointly developed by Google and other manufacturers. It can support the running of Java applications that have been converted into. Dex (i.e. Dalvik Executable) format. Dex format is a compression format specially designed for Dalvik applications, suitable for systems with limited memory and processor speed. Dalvik is optimized to allow multiple instances of virtual machines to run simultaneously in limited memory, and each Dalvik application executes as a separate Linux process. A separate process prevents all programs from being shut down in the event of a virtual machine crash.

What is ART: The Android operating system has matured, and Google’s Android team is turning its attention to some underlying components, one of which is the Dalvik runtime, which is responsible for running applications. Google developers have spent two years developing a faster, more efficient and power-efficient alternative ART runtime. ART stands for Android Runtime and handles application execution In a completely different way than Dalvik, which relies on a just-in-time (JIT) compiler to interpret bytecode. Developers compile application code that runs on users’ devices through an interpreter, which is not efficient, but makes it easier to run applications on different hardware and architectures. ART changes this completely by precompiling the bytecode into the machine language at application installation, a mechanism called Ahead-of-time (AOT) compilation. By removing the process of interpreting code, the application executes more efficiently and starts faster.

ART strengths:

Significantly improved system performance Applications start up faster, run faster, experience smoother, and have more timely tactile feedback. Longer battery life supports lower hardware

ART disadvantages: Larger storage footprint, which may increase application installation time by 10%-20%

Scroller principle

There are three core methods in the Scroller implementation process

MScroller.com puteScrollOffset mScroller. StartScroll () () view.com puteScroll. (1), in mScroller startScroll () for sliding made some initialization, such as: Start coordinates, distance and direction of slide and duration (default), animation start time, etc.

2, mScroller.com puteScrollOffset () method is mainly based on the current time has faded to calculate the coordinates of the current point. Since the animation time is set in mscroll.startScroll (), the computeScrollOffset() method can easily obtain the position of the current moment based on the elapsed time and store it in the variables mCurrX and mCurrY. In addition, this method can determine whether the animation is over.

Java and JavaScript interact in Android

webView.addJavaScriptInterface(new Object(){xxx}, "xxx"); 1 Answer: JavaScript scripts can be executed using WebView controls, and Java code can be executed in JavaScript. If you want to let the WebView control execute JavaScript, you need to call WebSettings. SetJavaScriptEnabled method, the code is as follows:  WebView webView = (WebView)findViewById(R.id.webview); WebSettings webSettings = webView.getSettings(); / / set the WebView support JavaScript webSettings. SetJavaScriptEnabled (true); webView.setWebChromeClient(new WebChromeClient()); JavaScript call Java methods require the use of a WebView. AddJavascriptInterface method sets the JavaScript call Java methods, the code is as follows: WebView. AddJavascriptInterface (new Object () {/ / JavaScript the method called public String process (String value) {/ / handling code return result; } }, "demo"); The process method can be called with the following JavaScript code: // Demo is a Java object mapped to a JavaScript object.Copy the code