titanium本身有提供建立native module的指令,可透過指令產出基本可以使用的template,然後再做修改。
可參考官方的quick start,或者直接參考以下教學:
建立一個android native module
建立一個android module
1
| ti create -p android -t module -d . -n test -u http:// --id com.example.test
|
build一個native java project
將build好的zip,解壓縮至titanium的module路徑
1
| unzip -o com.example.test-android-1.0.0.zip -d ~/Library/Application\ Support/Titanium/
|
KrollModule與KrollProxy
透過titanium的指令產生的native module,會建立出Module和Proxy兩個class,分別繼承KrollModule和TiViewProxy。其中會看到Kroll.method和Kroll.getProperty、Kroll.setProperty這些annotation,主要是會將method或者參數讓js去使用或存取寫入用。
取得剛建立好的native module
1
| var test = require('com.example.test');
|
若是在KrollModule宣告的Kroll.method這類annotation,將可直接讓js module存取
java code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @Kroll.module(name="Test", id="com.example.test") public class TestModule extends KrollModule {
@Kroll.method public String example() { return "hello world"; }
@Kroll.getProperty public String getExampleProp() { return "hello world"; }
@Kroll.setProperty public void setExampleProp(String value) { Log.d(LCAT, "set example property: " + value) }
}
|
js code
1 2 3
| Ti.API.info( test.example() ); Ti.API.info("module exampleProp is => " + test.exampleProp); test.exampleProp = "This is a test value";
|
若透過KrollProxy宣告的Kroll.method這類annotation,會先建立一個instance,在讓js使用
java code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| @Kroll.proxy(creatableInModule=TestModule.class) public class ExampleProxy extends TiViewProxy {
@Override public TiUIView createView(Activity activity) { TiUIView view = new ExampleView(this); view.getLayoutParams().autoFillsHeight = true; view.getLayoutParams().autoFillsWidth = true; return view; }
@Kroll.method public void printMessage(String message) { Log.d(LCAT, "printing message: " + message); } @Kroll.getProperty @Kroll.method public String getMessage() { return "Hello World from my module"; } @Kroll.setProperty @Kroll.method public void setMessage(String message) { Log.d(LCAT, "Tried setting module message to: " + message); }
}
|
js code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| if (Ti.Platform.name == "android") { var proxy = test.createExample({ message: "Creating an example Proxy", backgroundColor: "red", width: 100, height: 100, top: 100, left: 150 }); proxy.printMessage("Hello world!"); proxy.message = "Hi world!. It's me again."; proxy.printMessage("Hello world!"); win.add(proxy); }
|
java code
1 2 3 4 5 6
| @Kroll.method public void testCallback(KrollFunction cb) { KrollDict dict = new KrollDict(); dict.put("test", 123); cb.callAsync( getKrollObject(), dict ); }
|
js code
1 2 3 4 5 6 7 8 9
| test.testCallback(function( evt ){ Ti.API.info(arguments.length); Ti.API.info(evt); Ti.API.info(JSON.stringify( evt )); Ti.API.info(evt.test); });
|
以上的程式碼皆為片段。