在CordovaActivity中添加原生View组件

Windows 24H2升级后eNSP AR_40报错40?VirtualBox虚拟化修复指南 虚拟化技术通过Hypervisor在操作系统与硬件间建立抽象层,使虚拟机能够共享物理资源。其核心原理依赖CPU的VT-x/AMD-V指令集,而Windows 24H2对内核隔离与驱动签名的强化会直接占用或拦截这些虚拟化资源。在工程实践中,VirtualBox作为Type-2型Hypervisor,常因内存完整性开启或版本过旧导致虚拟网卡创建失败,进而引发设备启动中断。典型场景包括网络仿真实验、多系统测试环境搭建等。当eNSP的AR_40路由器依赖VirtualBox引擎时,24H2的安全策略变更便会触发错误 阅读详情


今天把移动Web站封装成了Android App,发现还是用Cordova封装方便,即使没有使用到任何原生的API, 主要是兼容性好,配置比用系统WebView方便太多了。
默认继承的CordovaActivity只有一个WebView,因此没有不方便通过java代码添加View,通过重新makeWebView,createViews 2个方法可以实现使用自定义的layout, 方便的添加自己的原生组件。


代码如下
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageButton;

import org.apache.cordova.CordovaActivity;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewImpl;
import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.engine.SystemWebViewEngine;

public class MainActivity extends CordovaActivity {


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        super.init();
        loadUrl(launchUrl);
        ImageButton btnShare=(ImageButton)findViewById(R.id.btnShare);

        btnShare.setAlpha(0f);
        btnShare.animate()
                .alpha(1f)
                .setDuration(1500)
                .setInterpolator(new DecelerateInterpolator())
                .setStartDelay(1000);

        btnShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
                intent.putExtra(Intent.EXTRA_TEXT, "欢迎访问");
                startActivity(Intent.createChooser(intent, "分享到"));
            }

        });
    }

    @Override
    protected CordovaWebView makeWebView() {
        SystemWebView webView = (SystemWebView)findViewById(R.id.cordovaWebView);
        return new CordovaWebViewImpl(new SystemWebViewEngine(webView));
    }

    @Override
    protected void createViews() {
        //Why are we setting a constant as the ID? This should be investigated
//        appView.getView().setId(100);
//        appView.getView().setLayoutParams(new FrameLayout.LayoutParams(
//                ViewGroup.LayoutParams.MATCH_PARENT,
//                ViewGroup.LayoutParams.MATCH_PARENT));
//
//        setContentView(appView.getView());

        if (preferences.contains("BackgroundColor")) {
            int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK);
            // Background of activity:
            appView.getView().setBackgroundColor(backgroundColor);
        }

        appView.getView().requestFocusFromTouch();
    }

}


更详细的介绍看下面的文章:

Embed Cordova Webview in Android Native App

Some articles have shown how to embed cordova webview to android native application, for example:

But unfortunately, the latest release of cordova android(4.0.0) make big changes on its code base. This changes, mostly kind of design pattern, have made the methods described in above article not work. What make me confused is that the cordova official website still use the old method in its example, which may waste others a lot of time.

This article will show how to cooperate with the new changes of cordova android to embed cordova webview in native android application.

Create Cordova Android Project

First of all, we need to create a cordova android project. It is better to use cordova-cli.

cordova create test_cordova com.example.hello HelloWorld
cordova platform add android
cordova plugin add nl.x-services.plugins.toast
cordova plugin add org.apache.cordova.device
cordova build
  • The first line of code create a new cordova project in folder test_cordova.
  • The second line of code add android platform for new created project.
  • The third and fourth line of code add two plugin for project(we will use these plugins in the example).
  • The last line of code build the new created project

Create Native Android Application

Google now suggest Android Studio for building android project, so we will use it here. Create a new project with blank activity using Android Studio. Here, the new created activity is called MainActivity.

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void startCordovaActivity(View view) {
        Intent intent = new Intent(this, TestCordovaActivity.class);
        startActivity(intent);
    }

    public void startCordovaActivityWithLayout(View view) {
        Intent intent = new Intent(this, TestCordovaWithLayoutActivity.class);
        startActivity(intent);
    }

}

Nothing special, we just define two methods: startCordovaActivity and startCordovaActivity. These two method is bind with two buttons, which we will see later.

  • startCordovaActivity will transfer to a new activity whose layout is a cordova webview created programmaticly.
  • startCordovaActivity will transfer to a new activity whose layout is defined using xml layout file and embedded with a cordova webview.

Lets have a look at MainActivity's layout xml file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:text="Start Cordova Activity Without Layout"
        android:onClick="startCordovaActivity"
        android:layout_width="200dp"
        android:layout_height="100dp" />

    <Button
        android:text="Start Cordova Activity With Layout"
        android:onClick="startCordovaActivityWithLayout"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:layout_marginTop="50dp"/>

</LinearLayout>

Two buttons are defined, corresponding to the two methods above.

TestCordovaActivity

This activity is created to show how to create an activity with a cordova webview without the need of layout xml file.

public class TestCordovaActivity extends CordovaActivity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.init();
        // Load your application
         launchUrl = "file:///android_asset/www/index.html";
//        launchUrl = "file:///android_asset/www/index2.html";
        loadUrl(launchUrl);
   }
}

Noted that we extends the CordovaActivity , which is from cordova library and implement most of stuff in order to cooperate with a cordova webview. We don't need to set the layout xml file usingsetContentView here, because the CordovaActivity create set it for us, a default cordova webview.

TestCordovaWithLayoutActivity

This activity has its layout xml file.

public class TestCordovaWithLayoutActivity extends CordovaActivity {


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_cordova_with_layout);
        super.init();
        // Load your application
        // launchUrl = "file:///android_asset/www/index.html"
        launchUrl = "file:///android_asset/www/index2.html";
        loadUrl(launchUrl);
    }

    @Override
    protected CordovaWebView makeWebView() {
        SystemWebView webView = (SystemWebView)findViewById(R.id.cordovaWebView);
        return new CordovaWebViewImpl(new SystemWebViewEngine(webView));
    }

    @Override
    protected void createViews() {
        //Why are we setting a constant as the ID? This should be investigated
//        appView.getView().setId(100);
//        appView.getView().setLayoutParams(new FrameLayout.LayoutParams(
//                ViewGroup.LayoutParams.MATCH_PARENT,
//                ViewGroup.LayoutParams.MATCH_PARENT));
//
//        setContentView(appView.getView());

        if (preferences.contains("BackgroundColor")) {
            int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK);
            // Background of activity:
            appView.getView().setBackgroundColor(backgroundColor);
        }

        appView.getView().requestFocusFromTouch();
    }

}

Again, we need to extend the CordovaActivity. But this time, we use setContentView to set layout xml explicitly. In order to make things work, we need to override two methods: makeWebView andcreateViews.

  • makeWebView is important, it use the R.id.cordovaWebView, which we define in layout xml file(we will see later).
  • createViews is not so important, we override it just because it will use setContentView by default. But we want to use our xml, so just comment it.

The activity_test_cordova_with_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.jimmy.embeddedcordovawebviewdemo.TestCordovaWithLayoutActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="#FF0000"
        android:textColor="#FFFFFF"
        android:gravity="center"
        android:text="This is native text view"
        />

    <org.apache.cordova.engine.SystemWebView
        android:id="@+id/cordovaWebView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</LinearLayout>

We use a org.apache.cordova.engine.SystemWebView from cordova library. If you have read the articles listed above, you may remember that most of examples use org.apache.cordova.CordovaWebView. For example, below xml file is used in cordova official site.

<org.apache.cordova.CordovaWebView
     android:id="@+id/tutorialView"
     android:layout_width="match_parent"
     android:layout_height="match_parent" />

This still works until release 4.0.0 ... Now, the CordovaWebView class has changed to an interface. So we can not use like this anymore.

Copy Cordova Android Project to Native Android Application

Now comes the most excited part, we need to copy useful stuff of cordova project to the native android project.

cordova jar

The first and most important thing is that we need a cordova lib. You can download the latest cordova android 4.0.0 package, then create a jar file. Check the cordova offiicial website.

Navigate to the Android package's /framework directory and run ant jar. It creates the Cordova .jar file, formed as /framework/cordova-x.x.x.jar.

After creating the jar file, we need to import it into our Android Studio project. Copy the jar file to libsfolder and add the follow line in build.gradle.

compile files('libs/cordova-4.0.0.jar')

Try to access the class in cordova lib after you finish to see if everything is ok.

www folder

Copy the www folder in cordova project to the android project. Note that the folder structure on the right is for Android Studio.

platforms/android/assets/www -> src/main/assets/www

plugins

We have added plugins for cordova project above, so we need to add them to our android project.

We need to use the cordova plugins in folder platforms/android/src/, instead of plugins/, because when you run cordova build, cordova will copy the plugins in folder plugins/ to folderplatforms/android/src/ and perform some magic under the table(the config.xml indeed).

platforms/android/src/plugin_folder -> src/main/java/ 

config.xml

Cordova use the config.xml for its configuration, likes plugins declarations. Note that do NOT use the file in root path of cordova project, use that in platforms folder instead.

platforms/android/res/xml/config.xml -> src/main/res/xml/

Bonus

You can checkout the final project in github.

华为OD机试真题 新系统【优化充电桩调度算法】 华为OD机试 新系统真题【优化充电桩调度算法】,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试真题【优化充电桩调度算法】 阅读详情

相关推荐

微生物组β-多样性——PCoA分析及可视化

让你的数据映入眼帘

qq_47369980的博客 1万+

Cordova源码解析(2)_CordovaActivity分析

上一篇讲述了cordova工程的创建,并成功运行起来,那cordova是如何加载html页面的,本文就来详细分析一下。 MainActivity 分析 App的入口是MainActivity,打开MainActivity可以看到是继承于CordovaActivity,在onCreate中的loadUrl方法和launchUrl属性都是从CordovaActivity中继承来的,所以CordovaA...

renzhongrui的博客 1148

Multisim 14.0实战:从零搭建可调幅多波形信号发生器(附仿真文件)

本文详细介绍了如何在Multisim 14.0中从零搭建一个可调幅多波形信号发生器,涵盖方波、三角波和正弦波的生成原理与实现步骤。通过核心电路架构解析、关键参数设计及Multisim实战操作,帮助电子工程学习者和硬件工程师掌握信号发生器的设计与调试技巧,并提供仿真文件供实践验证。

nokia的博客 1079

cordova与activity通信

cordova与activity通信

yangshiman的专栏 3463

在Windows10上安装WSL2

WSL2是微软提供的Windows子系统,允许在Windows 10和11上运行Linux环境,提供更好的性能和兼容性。安装WSL2需要启用WSL功能、更新系统、安装WSL2内核,并设置为默认版本。之后,可以通过Microsoft Store安装Linux发行版,并使用WSL命令启动和管理它们。

howard2005的专栏 5954

Python 爬虫实战:付费 IP 代理使用技巧与爬虫稳定性优化

付费IP代理实战指南:突破反爬与优化稳定性 本文系统讲解付费IP代理在爬虫项目中的高效应用方法。首先对比分析静态代理、动态代理和隧道代理的优缺点及适用场景,推荐高并发项目优先选择隧道代理。然后详细演示了主流代理服务商的集成方法,包括代理池的自动更新和健康检测机制。核心部分重点介绍了爬虫稳定性优化策略,如智能重试、频率控制和请求间隔优化等关键技术。最后通过压力测试验证优化效果,并提供成本控制方案,包括代理复用、错峰爬取等实用技巧。通过本教程,开发者可有效解决高并发爬虫中的IP封禁问题,显著提升系统稳定性和抗风

2503_91057718的博客 2456

Cordova系列之化繁为简:打造全场景适用的Cordova组件

一个基于Cordova封装的全场景组件,使用简单,在保留Cordova原有功能的基础上突破了必须继承CordovaActivity的限制。支持在Fragment中使用,还能能作为自定义view使用,提供关键节点的事件回调,可快速基于Cordova实现业务需求。

喻志强的博客 9580

【局部路径规划模块地图算法】基于势场地图的VFH、VFH+、VFH*算法(附C++代码)

认知有限,望大家多多包涵,有什么问题也希望能够与大家多交流,共同成长!本文先对基于地图的方法–VFH、VFH+、VFH*算法做个简单的介绍,具体内容后续再更,其他模块可以参考去我其他文章提示:以下是本篇文章正文内容。

qq_35635374的博客 1690

Cordova Android源代码分析系列一(项目总览和CordovaActivity分析)

版权声明:本文为博主offbye西涛原创文章。未经博主同意不得转载。 https://blog.csdn.net/offbye/article/details/31776833 ...

weixin_30642869的博客 204

Python 爬虫实战:微博自动化运营工具(点赞 / 转发 / 评论 + 反封号策略)

微博作为中国最大的社交媒体平台之一,拥有庞大的用户群体和丰富的数据资源。通过 Python 爬虫技术,我们可以实现微博的自动化运营,包括点赞、转发、评论等功能,同时采取有效的反封号策略,确保账号的安全和稳定运行。

u014481728的博客 1181

AI测试:手把手教你用AI生成测试用例并支持导出Excel「喂饭教程」

如果我告诉你,有一种方法,你只需要输入需求内容,AI就能自动帮你设计出结构清晰、覆盖全面的测试用例,并直接生成一份精美的Excel表格,你会不会心动?

blues_C的博客 3890

Cordova android框架详解

Cordova android框架详解 转载自http://www.cnblogs.com/hubcarl/p/4202784.html 一、Cordova 核心java类说明   CordovaActivity:Cordova Activity入口,已实现PluginManager、WebView的相关初始化工作, 只需继承CordovaActivity实现自己的业务需求

qingfeng2556的博客 1542

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

Android项目里集成Cordova详解

自定义cordova插件;Android studio环境下将CordovaLib作为依赖导入;自定义Cordova插件;cordova自定义java类中的一些问题;在CordovaActivity中添加原生View组件;在Fragment里使用CordovaWebView;Fragment拦截返回键

备忘录 2万+

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

PhoneGap 底层框架实现原理 详解

PhoneGap能实现跨平台,并且拥有强大的跨平台访问设备接口的能力,无非就是通过大家都有的WebView组件,实现了HTML5+CSS3+JS的解析,这也是跨平台移动开发相对于原生开发最大的优势,一套代码,大部分平台共用~ 那么,PhoneGap的底层框架原理究竟是什么样的呢?下面我们就来一起探讨一下~~ 若抛弃其原理,那么在我们的开发中,JS与Java之间的调用方式(插件开发)可参考这篇文

LeBron_Six的专栏 1万+

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

最终版本

/*        Licensed to the Apache Software Foundation (ASF) under one        or more contributor license agreements.  See the NOTICE file        distributed with this work for additional information

拥有梦想的技术青年的专栏 1628

ionic android 禁止截屏设置

禁止截屏设置:getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE); 例子:需要引入包 ionic 开发 修改platforms\android\CordovaLib\src\org\apache\cordova\CordovaActivity.java 文件内容

yang__Y的博客 1368

Cordova4.2.0处理 Failed to request GL process. Deadlock likely

修改文件:CordovaApp-CordovaLib项目&gt;org.apache.cordova包&gt;CordovaActivity.java WebView对象(appView)初始化init()&gt;appView = webView != null ? webView : makeWebView();后加 appView.setLayerType(View.LAYER_TYPE...

CSDN_LuoYang的博文 1465

java webview事件_捕获“页面已完成加载”事件,并使用xwalk Webview在ionic / cordova MainActivity.java中进行操作...

我有一个android应用程序,它是使用ioic构建的,我在其中使用了xwalk web视图。我需要在扩展MainActivity.java类的CordovaActivity中捕获page finished loading事件,然后执行一些操作。我该怎么做。最佳答案:如果您在crosswalk嵌入式模式下使用xwalkview,那么它的api xwalkresourceclient\onloadf...

weixin_30916653的博客 307

Cordova集成android原生应用

首先你得要有一个cordova的项目,因为太多太多的东西需要从那里复制粘贴了。。。 那我们就开始吧! 第一步:打开你的android原生项目; 第二步:将Cordova项目的Cordovalib导入安卓项目,并在app的build.gradle中添加依赖; 第三步:在main文件夹下创建assets文件夹,然后将Cordova项目的H5端代码(即WWW文件夹)拷贝到assets里面; 第四步...

qq_35213765的博客 886

Cordova系列之初探Cordova

了解cordova的优势以及不足,如何摆脱必须继承CordovaActivity的限制,怎么封装一个比较好用的组件

喻志强的博客 5604

Phonegap Android 项目使用Cordova

要在已经创建好的Android项目里,使用Cordova。 1. 首先在Android Studio中创建Android项目 2. 创建cordova项目 cordova crate test com.example test 创建cordova项目的目的是为了在Android项目中使用cordova生成的文件. 然后增加android平台 cor...

weixin_34259559的博客 115

Cordova 自定义页面

Cordova 自定义页面的 当使用cordova与html交互的架构。有想自定义的布局 package com.rzt.micro3.activity; import android.graphics.Color; import android.os.Bundle; import com.youotech.demo.R; import org.apache.cordova.CordovaActivity; import org.apache.cordova.CordovaWebView; im

亦然莹儿的博客 393

山山水水

/*        Licensed to the Apache Software Foundation (ASF) under one        or more contributor license agreements.  See the NOTICE file        distributed with this work for additional information

拥有梦想的技术青年的专栏 1685

cordova 在android的端使用

目的:将h5开发的功能模块嵌入到原生android中 打开h5端开发的cordova应用的文件夹 进入platforms文件夹 进入android 将里面的CordovaLib作为一个modle导入我们的原生项目并添加为依赖; 接着将assets目录中的www文件夹复制到我们原生项目里的assets目录下,这里面就是h5小伙伴提供给我们的资源,需要我们去调用; 接着我们打开sr

qq_23412151的博客 1469

Phonegap 插件调用本地流程分析(一)

为什么80%的码农都做不了架构师?>>> ...

weixin_34124939的博客 133

Android用PhoneGap封装webapp在android代码中实现连按退出和loadingpage

用PhoneGap封装后的程序有一些瑕疵,比如启动时黑屏,菜单按钮和返回按钮不好控制等。 PhoneGap也在github提交的它的源码(版本:2.8): https://github.com/apache/cordova-android/tree/master/framework/src/org/apache/cordova 先说loadingpage,其实在phonegap提供...

diaohundi8422的博客 311
上一篇: 技术贴:开源飞控那些事
下一篇: Android开发中的armeabi和armeabi-v7a介绍
offbye
offbye 领域专家: 操作系统技术领域 领域专家: 操作系统技术领域
博客等级 码龄24年 1309粉丝 252原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

offbye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址