说明:本次说的系统服务,是指捆绑在system_process进程中的服务。
仔细阅读源码可以发现,在frameworks/base/services/java/com/android/server/SystemServer.java中添加了很多服务,什么熵信息、电量、wife等等服务,这些服务启动都在launcher之前,一般要继承Binder或者继承一个AIDL。下面试着来添加一个简单系统服务
一。在frameworks/base/core/java/android/os/ 增加一个aidl文件,最后用aidl工具生产一个Java文件,这样可以方便后面:
package android.os;
/** * Interface that allows controlling and querying YtTts connectivity. * * {@hide} */ interface IYtTtsService{ /** * 播放Text文字 */ int speak(String text); }
然后在修改/frameworks/base/Android.mk,在LOCAL_SRC_FILES里添加一行:core/java/android/os/IYtTtsService.aidl \
不确定补充:把AIDL文件写在这个地方似乎可以避免加@hide
package com.android.server; import android.content.Context; import android.os.IYtTtsService; import android.os.RemoteException; import android.util.Log;
public class YtTtsService extends IYtTtsService.Stub { private WorkerThread mWorker; public YtTtsService(Context context) { super(); mWorker = new WorkerThread("YtTtsServiceWorker"); mWorker.start(); Log.i("[YT]", "In YtTtsService-->"+context); } @Override public int speak(String text) throws RemoteException { Log.i("[YT]", "In YtTtsService-->"+text); return 0; } private class WorkerThread extends Thread{ int i = 0; public WorkerThread(String name) { super(name); } public void run() { while(true){ i++; Log.i("[YT]", "In YtTtsService-->WorkerThread running "+i); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
try { Log.i("[YT]", "In SystemServer, YtTts add.."); ServiceManager.addService("yttts", new YtTtsService(context)); } catch (Throwable e) { Log.i("[YT]", "In SystemServer, YtTts add err.."); }
package cn.youngtone.tts; import android.content.Context; import android.os.IYtTtsService; import android.os.RemoteException; import android.util.Log; public class YtTtsManager { IYtTtsService service; public YtTtsManager(Context context ,IYtTtsService service) { this.service = service; } public void speak(String text) { try { Log.e("[YT]" , "In YtTtsManage-->speak():"+text); service.speak(text); } catch (RemoteException e) { Log.e("[YT]" , "In YtTtsManage-->E:RemoteException"); e.printStackTrace(); } } }
四。 在ContextImpl getSystemService中添加代码:
if ("yttts".equals(name)) {
if (mYtTtsManager == null) { IBinder b = ServiceManager.getService("yttts"); IYtTtsService service = IYtTtsService.Stub.asInterface(b); mYtTtsManager = new YtTtsManager(this, service); } return mYtTtsManager; }
五。测试代码
YtTtsManager mManager = (YtTtsManager)getSystemService("yttts"); mManager.speak("这是一个简单的系统服务!");
END.
参考:http://blog.csdn.net/aiai373824745/article/details/7439896