自定义Android核心服务实践
Daniel Wood 20101203
转载时请注明出处和作者
文章出处:http://danielwood.cublog.cn
作者:Daniel Wood
------------------------------------------------------------------------
5. 调用CalService服务
CalServiceTest.java文件
package com.example.android.simpleservice;//注意这个路径 import android.app.Activity; import android.os.Bundle; import android.widget.TextView;
public class CalServiceTest extends Activity { /** Called when the activity is first created. */ @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); int a = Native.add(1, 1); TextView tv = new TextView(this); tv.setText( "1 + 1 = " + String.valueOf(Native.add(1,1)) ); tv.append( " \n3 - 1 = " + String.valueOf(Native.sub(3,1)) ); tv.append( " \n2 * 3 = " + String.valueOf(Native.mul(2, 3)) ); tv.append( " \n4 / 2 = " + String.valueOf(Native.div(4, 2)) ); setContentView(tv); } } class Native{ static native int add(int a, int b); static native int sub(int a, int b); static native int mul(int a, int b); static native float div(int a, int b);
static { System.loadLibrary("JniCal"); //通过load方法得到动态库 } }
|
注意这个类中的Native类以及其路径,它就是在JNI层所对应的classPathName的类及路径。CalServiceTest.java的目录树为:
`-- src
`-- com
`-- example
`-- android
`-- simpleservice
`-- CalServiceTest.java
JNI中相关代码为:
static const char *classPathName = "com/example/android/simpleservice/Native";/
|
Android.mk文件
TOP_LOCAL_PATH:= $(call my-dir)
LOCAL_PATH:= $(TOP_LOCAL_PATH) include $(CLEAR_VARS)
LOCAL_MODULE_TAGS := samples
LOCAL_SRC_FILES := $(call all-subdir-java-files)
LOCAL_PACKAGE_NAME := CalServiceTest #App的名字
LOCAL_JNI_SHARED_LIBRARIES := libJniCal
include $(BUILD_PACKAGE) # Also build all of the sub-targets under this one: the shared library. include $(call all-makefiles-under,$(LOCAL_PATH))
|
通过make CalServiceTest得到apk:
target Package: CalServiceTest (out/target/product/generic/obj/APPS/CalServiceTest_intermediates/package.apk) adding: lib/ (stored 0%) adding: lib/armeabi/ (stored 0%) adding: lib/armeabi/libJniCal.so (deflated 71%) 'out/target/common/obj/APPS/CalServiceTest_intermediates/classes.dex' as 'classes.dex'... Install: out/target/product/generic/system/app/CalServiceTest.apk
|
在做完以上步骤时,你需要重新生成Android的文件系统镜像system.img,可以通过以下命令重新生成system.img:
out/host/linux-x86/bin/mkyaffs2image out/target/product/generic/system out/target/product/generic/system.img
|
|
|
|
|
然后启动模拟器。这时你运行CalServiceTest这个程序是没有任何现象的,因为CalService没有启动。通过adb shell进入到/system/bin目录,然后用./addserverapp启动服务。如果在使用./addserverapp命令的时候提示没有权限,那么退出shell,然后输入命令adb remount,然后再试试。
adb shell cd system cd bin ./addserverapp
|
这时再运行CalServiceTest就可以看到如下图片:
源代码下载
参考文献:
http://blog.chinaunix.net/u/22630/showart_2190320.html
http://dev.10086.cn/blog/?uid-49302-action-viewspace-itemid-477
----------------------------------------------------------------------
《完》
阅读(1988) | 评论(0) | 转发(0) |