所以我的经理似乎认为将应用程序从 2 个完全原生的 iOS 和 Android 应用程序转换为一个跨平台的 Angular/nativecript 应用程序是一项简单的任务(对我来说这听起来是一个糟糕的主意)。我正在尝试研究做到这一点所需的努力。我创建了一个 helloworld Nativescript 应用程序,我试图了解将现有 native 代码集成到 NativeScript 应用程序中的最佳方法是什么(基本上我想访问我的 native Web 服务功能)。我对这个主题的了解非常有限。
我看到有一种方法可以make your own native packages可以使用,但这似乎会花费很多精力并且麻烦/困惑。有没有办法只访问 nativescript 中的自定义 native java 对象?例如:
//Java
package com.tns;
public class TestObject {
public String doSomething () {
return "hello";
}
}
//Nativescript
import { Component } from "@angular/core";
declare var com: any
@Component({
selector: "my-app",
template: `
<ActionBar title="My App"></ActionBar>
<StackLayout orientation="vertical">
<Label [text]="message" (tap)="onTap()"></Label>
</StackLayout>
`
})
export class AppComponent {
public message: string = "Hello, Angular";
public onTap() {
this.message = "Text Changed";
var test = new com.tns.TestObject();
console.log(test.doSomething());
}
}
编辑:对于 future 的读者,上面的代码实际上现在可以工作
我认识你can do it只使用普通的 Android 类,但无法使用我自己的自定义类来做到这一点,也许我只是缺少一些东西(也许与导入有关?)。
我在尝试运行该程序时收到此错误
app/app.component.ts(21,24): error TS2304: Cannot find name 'com'.
我的对象就在我的项目的主文件夹下
基本上,他们希望我们一次将 Android 应用程序的某些部分转换为 NativeScript,同时保留所有旧的 native 功能,以便最终整个项目将转换为 NativeScript,从而为两个 ios 提供一个代码库理论上和安卓一样。在我看来,这听起来是一个非常糟糕的方法,应该从头开始。
TL;DR
如何在nativescript代码中使用自定义java类?
-----来自评论的补充------
An uncaught Exception occurred on "main" thread. com.tns.NativeScriptException: Calling js method onTouch failed
[object Object] File: "file:///data/data/org.nativescript.HelloWorld/files/app/tns_modules/tns-core-modules/ui/gestures/gestures.js, line: 97, column: 40
StackTrace: Frame: function:'GesturesObserver.androidOnTouchEvent', file:'file:///data/data/org.nativescript.HelloWorld/files/app/tns_modules/tns-core-modules/ui/gestures/gestures.js', line: 97, column: 41 Frame: function:'onTouch', file:'file:///data/data/org.nativescript.HelloWorld/files/app/tns_modules/tns-core-modules/ui/core/view.js', line: 113, column: 37
at com.tns.Runtime.callJSMethodNative(Native Method) at com.tns.Runtime.dispatchCallJSMethodNative(Runtime.java:1197) at com.tns.Runtime.callJSMethodImpl(Runtime.java:1061) at com.tns.Runtime.callJSMethod(Runtime.java:1047) at com.tns.Runtime.callJSMethod(Runtime.java:1028) ...
最佳答案
尝试排除那些圆括号:)与分配我在插件中使用的类相同。
编辑
它应该带有括号:D
var test = new com.tns.TestObject();
console.log(test.doSomething());
关于android - 如何在 NativeScript 中使用自定义 native Java 类/函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42016324/