下面的是上小节编写的程序,经过修改并且编译成功能正常运行的代码:
IHelloService.aidl/** {@hide} */
interface IHelloService
{
void sayhello();
int sayhello_to(String name);
}
HelloService.java
import android.util.Slog;
/* 实现Hello服务的函数 */
public class HelloService extends IHelloService.Stub {
private static final String TAG = "HelloService";
private int cnt1 = 0;
private int cnt2 = 0;
public void sayhello() throws android.os.RemoteException {
cnt1++;
Slog.i(TAG, "sayhello : cnt = "+cnt1);
}
public int sayhello_to(java.lang.String name) throws android.os.RemoteException {
cnt2++;
Slog.i(TAG, "sayhello_to "+name+" : cnt = "+cnt2);
return cnt2;
}
}
TestServer.java
import android.util.Slog;
import android.os.ServiceManager;
/* 1. addService
* 2. while(true) { read data, parse data, call function, reply }
*/
public class TestServer {
private static final String TAG = "TestServer";
public static void main(String args[])
{
/* add Service */
Slog.i(TAG, "add hello service");
ServiceManager.addService("hello", new HelloService());
while (true)
{
try {
Thread.sleep(100);
} catch (Exception e){}
}
}
}
TestClient.java
import android.util.Slog;
import android.os.ServiceManager;
import android.os.IBinder;
/* 1. getService
* 2. 调用服务的sayhello,sayhello_to
*
*/
/* test_client [name] */
public class TestClient {
private static final String TAG = "TestClient";
public static void main(String args[])
{
if (args.length == 0)
{
System.out.println("Usage: need parameter: [name]");
return;
}
if (args[0].equals("hello"))
{
/* 1. getService */
IBinder binder = ServiceManager.getService("hello");
if (binder == null)
{
System.out.println("can not get hello service");
Slog.i(TAG, "can not get hello service");
return;
}
IHelloService svr = IHelloService.Stub.asInterface(binder);
if (args.length == 1)
{
try {
svr.sayhello();
System.out.println("call sayhello");
Slog.i(TAG, "call sayhello");
} catch (Exception e) {}
}
else
{
try {
int cnt = svr.sayhello_to(args[1]);
System.out.println("call sayhello_to "+args[1]+" : cnt = "+cnt);
Slog.i(TAG, "call sayhello_to "+args[1]+" : cnt = "+cnt);
} catch (Exception e) {}
}
}
}
}
Android.mk
# Copyright 2008 The Android Open Source Project
#
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES := HelloService.java IHelloService.java TestServer.java
LOCAL_MODULE := TestServer
include $(BUILD_JAVA_LIBRARY)
include $(CLEAR_VARS)
LOCAL_SRC_FILES := HelloService.java IHelloService.java TestClient.java
LOCAL_MODULE := TestClient
include $(BUILD_JAVA_LIBRARY)
编译测试
把上述文件全部编写完成之后,所有文件都放在同一文件夹中,然后把该文件夹拷贝到frameworks\testing(如果没有,请自行创建)目录下,执行mmm命令,可以看到生产两个文件: out/target/product/qytech_azalea/system/framework/TestServer.jar out/target/product/qytech_azalea/system/framework/TestClient.jar 把这两个文件通过abd下载到开发板上执行: logcat TestServer:* TestClient:* HelloService:* *:S & CLASSPATH=./TestServer.jar app_process ./ TestServer & CLASSPATH=./TestClient.jar app_process ./ TestClient hello CLASSPATH=./TestClient.jar app_process ./ TestClient hello weidongshan