主要参考资料:自定义Android核心服务实践
http://blog.chinaunix.net/uid/24940434/frmd/101688/fup/101690.html
非常感谢“工藤*新一”博主,让我学到不少东西。
按照这篇文章,可以实现一个完整的服务,但是我有一下2个疑问:
1、整个服务(客户端)都是咋NDK层实现的,如果客户端使用Java来写该如何做呢?
2、如何让这个服务自动运行呢?
参看这篇文章可以解决以上2个疑问: http://blog.csdn.net/zfzf294990051/article/details/7361081
以下代码同样出自:http://blog.csdn.net/zfzf294990051/article/details/7361081
先来回答第一个疑问:
下面是大体实现代码:
1 package com.add.service; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.os.IBinder; 6 import android.os.Parcel; 7 import android.os.Process; 8 import android.util.Log; 9 import android.os.ServiceManager; 10 11 public class DM3730ADDServiceActivity extends Activity { 12 private static final String Tag = "com.add.service.test"; 13 /** Called when the activity is first created. */ 14 @Override 15 public void onCreate(Bundle savedInstanceState) { 16 super.onCreate(savedInstanceState); 17 setContentView(R.layout.main); 18 19 test(); 20 } 21 private void test() 22 { 23 try{ 24 IBinder binder = ServiceManager.getService("zhang"); 25 Parcel data = Parcel.obtain(); 26 Parcel reply = Parcel.obtain(); 27 if(binder == null){ 28 Log.d(Tag, "failed to get Service."); 29 } 30 data.writeInt(Process.myPid()); 31 data.writeInt(100); 32 binder.transact(0, data, reply, 0);//执行远程调用 33 Log.d(Tag, "result = "+reply.readInt());//验证结果 34 }catch(Exception e){ 35 e.printStackTrace(); 36 } 37 } 38 }
注:
1 ……………… 2 data.writeInt(Process.myPid()); 3 data.writeInt(100); 4 binder.transact(0, data, reply, 0);//执行远程调用 5 6 //如果直接使用上面定义的data,reply,这么使用才行。 7 data.recycle(); 8 reply.recycle(); 9 10 data = Parcel.obtain(); 11 reply = Parcel.obtain(); 12 data.writeInt(Process.myPid()); 13 data.writeInt(1200); 14 binder.transact(1, data, reply, 0);//执行远程调用 15 ………………
第二个疑问同样能再上面那个文章找到答案,我仍然做个记录:
修改启动脚本init.rc文件,使之在开机是启动服务addserver
1 #service addservice is a test 2 service addserver_zhang /system/bin/addserver