Cordova Source resolved (2) _CordovaActivity analysis

Disclaimer: This blog is mainly recorded some of the problems encountered by study notes and solutions, please indicate the source! https://blog.csdn.net/u010982507/article/details/86382103

Previous tells the story of cordovacreation of the project, and up and running successfully, how it cordova html page is loaded, the paper will analyze in detail.

MainActivity analysis

App inlet is MainActivityopen MainActivitycan be seen to be inherited CordovaActivity, the onCreate of loadUrlmethods and launchUrlproperties are the CordovaActivitysuccession to, so CordovaActivitythat cordovathe inlet.

public class MainActivity extends CordovaActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // enable Cordova apps to be started in the background
        // 获取外部传来的数据
        Bundle extras = getIntent().getExtras();
        if (extras != null && extras.getBoolean("cdvStartInBackground", false)) {
            moveTaskToBack(true);
        }
        // 加载html
        // Set by <content src="index.html" /> in config.xml
        loadUrl(launchUrl);
    }
}

CordovaActivity analysis

A, OnCreate method
into the CordovaActivityclass, you can see CordovaActivityinherited from Activitythis class is the completion of the basic configuration and initialization of cordova, according to the Activity life cycle, starting with the OnCreate start analyzing:
1, in OnCreate method is the first loadConfigmethod ,As follows:

protected void loadConfig() {
    ConfigXmlParser parser = new ConfigXmlParser();
    parser.parse(this);
    preferences = parser.getPreferences();
    preferences.setPreferencesBundle(getIntent().getExtras());
    launchUrl = parser.getLaunchUrl();
    pluginEntries = parser.getPluginEntries();
    Config.parser = parser;
}

loadConfig method first initializes the ConfigXmlParserclass, but ConfigXmlParserthe main attributes and methods are:

  • CordovaPreferencesClass: responsible for parsing config.xmlthe <preference name="loglevel" value="DEBUG" />node;
  • launchUrlProperty Value: The default is file:///android_asset/www/index.html;
  • setStartUrl method of: determining config.xmlwhether the configuration <content src="index.html" />;
  • parseMethods: resolved under the res / xml directory config.xmlfile

2. After the initial configuration, then initialize the log, log level setting.

String logLevel = preferences.getString("loglevel", "ERROR");
LOG.setLogLevel(logLevel);

3, further down is the configuration window full screen or, if there is a title.

if (!preferences.getBoolean("ShowTitle", false)) {
    getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}
if (preferences.getBoolean("SetFullscreen", false)) {
    LOG.d(TAG, "The SetFullscreen configuration is deprecated in favor of Fullscreen, and will be removed in a future version.");
    preferences.set("Fullscreen", true);
}
if (preferences.getBoolean("Fullscreen", false)) {
    // NOTE: use the FullscreenNotImmersive configuration key to set the activity in a REAL full screen
    // (as was the case in previous cordova versions)
    if (!preferences.getBoolean("FullscreenNotImmersive", false)) {
        immersiveMode = true;
    } else {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
} else {
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}

Two, loadUrl method
loadUrl in MainActivity method is called in this method implementation is as follows:

public void loadUrl(String url) {
    if (appView == null) {
        init();
    }
    // If keepRunning
    this.keepRunning = preferences.getBoolean("KeepRunning", true);
    appView.loadUrlIntoView(url, true);
}

This method first performs a init()method, created appView is webview instance in the init method is executed as follows:

appView = makeWebView();

The makeWebView () method in the realization of the CordovaWebViewImplinstance, as the name suggests, this class is the CordovaWebViewimplementation class, keep after the talk.

protected CordovaWebView makeWebView() {
    return new CordovaWebViewImpl(makeWebViewEngine());
}

protected CordovaWebViewEngine makeWebViewEngine() {
    return CordovaWebViewImpl.createEngine(this, preferences);
}

It creates an instance of the webview appView, followed by CordovaActivity set the layout of the method execution is createViews()on, after setting the layout, and then perform the initialization and initialization of appView of cordovaInterface down, these classes are talking about the future.
After reading the init method, further down is the use of the webview to load url html

appView.loadUrlIntoView(url, true);

Three, Activity life-cycle approach
key method in CordovaActivity are those, of course, there are many methods described above, but all of them inherited methods, look at the following list:

  • onPause
  • onNewIntent
  • onResume
  • onStop
  • onStart
  • onDestroy
    life-cycle approach These are Activity in these methods, it implements a method corresponding webview, these methods are in fact handling of plug-ins. Such as:
@Override
protected void onStart() {
    super.onStart();
    LOG.d(TAG, "Started the activity.");

    if (this.appView == null) {
        return;
    }
    this.appView.handleStart();
}

OnStart method CordovaActivity performed in the this.appView.handleStart();method, and the handleStartmethod is implemented in

@Override
public void handleStart() {
    if (!isInitialized()) {
        return;
    }
    pluginManager.onStart();
}

After analyzing these CordovaWebViewImplinstructions again in detail when this class.

Four, Activity inherited methods
in addition to the life-cycle approach, as well as

  • startActivityForResult
  • onActivityResult
  • onRequestPermissionsResult
  • onSaveInstanceState
  • onWindowFocusChanged
  • onConfigurationChanged
  • onOptionsItemSelected
  • onPrepareOptionsMenu
  • onCreateOptionsMenu

Activity of these methods are inherited, we are familiar with do not explain.

Four, onReceivedError inherited methods
revisit a more important method below: error handling page.
There is in CordovaActivity the onReceivedErrormethod, which is to deal with the current html page error, and will jump to another page displays an error message, similar to when accessing the page can not be found, display a 404 page.

public void onReceivedError(final int errorCode, final String description, final String failingUrl) {
     final CordovaActivity me = this;

     // If errorUrl specified, then load it
     final String errorUrl = preferences.getString("errorUrl", null);
     if ((errorUrl != null) && (!failingUrl.equals(errorUrl)) && (appView != null)) {
         // Load URL on UI thread
         me.runOnUiThread(new Runnable() {
             public void run() {
                 me.appView.showWebPage(errorUrl, false, true, null);
             }
         });
     }
     // If not, then display error dialog
     else {
         final boolean exit = !(errorCode == WebViewClient.ERROR_HOST_LOOKUP);
         me.runOnUiThread(new Runnable() {
             public void run() {
                 if (exit) {
                     me.appView.getView().setVisibility(View.GONE);
                     me.displayError("Application Error", description + " (" + failingUrl + ")", "OK", exit);
                 }
             }
         });
     }
 }

The method for processing logic determines whether config.xmlthe page is configured errorUrl, if the configuration errorUrl, then jump to this point url html pages, as follows:

me.appView.showWebPage(errorUrl, false, true, null);

If no configuration is hidden away webview, and call the displayErrormethod

me.appView.getView().setVisibility(View.GONE);
me.displayError("Application Error", description + " (" + failingUrl + ")", "OK", exit);

displayErrorImplementation is very simple, in fact, to create a AlertDialog message.

public void displayError(final String title, final String message, final String button, final boolean exit) {
    final CordovaActivity me = this;
    me.runOnUiThread(new Runnable() {
        public void run() {
            try {
                AlertDialog.Builder dlg = new AlertDialog.Builder(me);
                dlg.setMessage(message);
                dlg.setTitle(title);
                dlg.setCancelable(false);
                dlg.setPositiveButton(button,
                        new AlertDialog.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                if (exit) {
                                    finish();
                                }
                            }
                        });
                dlg.create();
                dlg.show();
            } catch (Exception e) {
                finish();
            }
        }
    });
}

This, CordovaActivity the end of the analysis, some details may not analyze that these will leave you thinking about it myself.

Guess you like

Origin blog.csdn.net/u010982507/article/details/86382103