Cordova/phonegap activity lifecycle

2019-05-29 23:09发布

问题:

I'm working on a map plugin for android in a cordova application (let's forget for a second that there is already more than one in the wild, and consider this an academical question), the documentation for MapView states:

Users of this class must forward all the life cycle methods from the Activity or Fragment containing this view to the corresponding ones in this class. [...]

That is, I need to appropriately call on my map at least the

onResume()
onPause()
onDestroy()
onLowMemory()

methods. Is there a way to do that with Cordova/Phonegap? Keep in mind that I'm working in a subclass of CordovaPlugin, as with every plugin, and not in the Activity proper (which I cannot touch, code-wise at least).

Thank you!

回答1:

How silly of me: the CordovaPlugin class forwards the methods:

public void onPause(boolean multitasking)
public void onResume(boolean multitasking)
public void onDestroy()

among the others, which answers my question. All you need to do is implement them in the plugin and at least part of the lifecycle can be handled in this way.

As for the missing methods (onCreate, onRestart, etc), having them would make no sense, as the cordova activity is already created when whatever plugins enters the game.

Hope this helps anyone with the same problem



回答2:

Little bit clarification for Rick77's answer

In javascript file we have to mention

document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("pause", onPause, false);
document.addEventListener("resume", onResume, false);

Then write the functions like below

function onDeviceReady() {
    console.log("onDeviceReady");
}

function onPause() {
    console.log("onPause");
}

function onResume() {
    console.log("onResume");
}

To check the log, follow the bellow steps (While checking the log, Connect the mobile to pc and open the app)

Step 1: copy chrome://inspect/#devices and paste in chrome then you will get the page like

Step 2: Click on inspect

Step 3: Then chrome will opens the new window like

We can check the log here (Top right hand side (Marked in red color))