在Android中,应用访问service提供的接口都是通过AIDL(Android Interface Definition Language),可以理解为一种规范,甚至可以粗陋的理解为C语言里面的.h文件,如果你曾经是一名C语言开发者,而且只是使用的话。下面的例子是想增加获取cpu 频率的service及其对应的AIDL,其中并没有实际的读取频率和设置governor的操作,仅仅用于演示如何在framework中增加一个service和AIDL。
1) 增加AIDL接口文件
文件:frameworks/base/core/java/android/os/ICpuFreqService.aidl
package android.os;
import android.os.WorkSource;
/** @hide */
interface ICpuFreqService
{
int getCurGovernor();
int getCurFrequency();
}
2) 在Android.mk中增加ICpuFreqService.aidl接口文件的编译选项
文件:frameworks/base/Android.mk
LOCAL_SRC_FILES += \
……….
core/java/android/os/ICpuFreqService.aidl\
……..
3) 实现CpuFreqService.java
文件:frameworks/base/services/java/com/android/server$ ls CpuFreqService.java
package com.android.server;
import android.os.ICpuFreqService;
class CpuFreqService extendsICpuFreqService.Stub{
static int EnterTimes=0;
public int getCurGovernor()
{
return0x11233;
}
public int getCurFrequency()
{
EnterTimes++;
return (EnterTimes*50);
}
}
4) 在SystemService中注册service
文件:frameworks/base/services/java/com/android/server/SystemServer.java
CpuFreqService cpufreq=null;
………………
Slog.i(TAG, "CpuFreq Manager");
cpufreq = new CpuFreqService();
ServiceManager.addService("cpufreq",cpufreq);
5) 在APP中调用AIDL接口
…………….
import android.os.ServiceManager;
import android.os.ICpuFreqService;
……………...
try {
ICpuFreqService cpuFreq=
ICpuFreqService.Stub.asInterface( ServiceManager.getService("cpufreq"));
setSummaryText("baseband_version",Integer.toString(cpuFreq.getCurGovernor()));
Log.e("Status","Governor=" + Integer.toString(cpuFreq.getCurGovernor()));
Log.e("Status","Freq ="+ Integer.toString(cpuFreq.getCurFrequency()));
} catch (Exception e)
{
}
或者可以使用借壳一个Managner,如PackageManagner
private Method mGetPackageSizeInfoMethod;
mGetPackageSizeInfoMethod = mContext.getPackageManager().getClass().getMethod(
"getPackageSizeInfo", String.class, IPackageStatsObserver.class);
try {
mGetPackageSizeInfoMethod.invoke(mContext.getPackageManager(), new Object[]{
packname,
new IPackageStatsObserver.Stub() {
@Override
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
synchronized (appInfo) {
appInfo.setPkgSize(pStats.cacheSize + pStats.codeSize + pStats.dataSize);
}
}
}
});
} catch (Exception e) {
}