Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 初級開發 >> Android添加一個系統service

Android添加一個系統service

編輯:初級開發

Specifying the interface.

This example uses aidl, so the first step is to add an interface definition file:

frameworks/base/core/Java/android/os/IEneaService.aidl

package android.os;

interface IEneaService {

/**

* {@hide}

*/

void setValue(int val);

}

The interface file will need to be added to the build system:

frameworks/base/android.mk

Add the following around line 165 (the end of the list of SRC_FILES):

core/Java/android/os/IEneaService.aidl

Implementing the server

The service spawns a worker thread that will do all the work, as part of the system server process. Since the service is created by the system server, it will need to be located somewhere where the system server can find it.

frameworks/base/services/java/com/android/server/EneaService.Java

package com.android.server;

import android.content.Context;

import android.os.Handler;

import android.os.IEneaService;

import android.os.Looper;

import android.os.Message;

import android.os.Process;

import android.util.Log;

public class EneaService extends IEneaService.Stub {

private static final String TAG = "EneaService";

private EneaWorkerThread mWorker;

private EneaWorkerHandler mHandler;

private Context mContext;

public EneaService(Context context) {

super();

mContext = context;

mWorker = new EneaWorkerThread("EneaServiceWorker");

mWorker.start();

Log.i(TAG, "Spawned worker thread");

}

public void setValue(int val)

{

Log.i(TAG, "setValue " + val);

Message msg = Message.obtain();

msg.what = EneaWorkerHandler.MESSAGE_SET;

msg.arg1 = val;

mHandler.sendMessage(msg);

}

private class EneaWorkerThread extends Thread{

public EneaWorkerThread(String name) {

super(name);

}

public void run() {

Looper.prepare();

mHandler = new EneaWorkerHandler();

Looper.loop();

}

}

private class EneaWorkerHandler extends Handler {

private static final int MESSAGE_SET = 0;

@Override

public void handleMessage(Message msg) {

try {

if (msg.what == MESSAGE_SET) {

Log.i(TAG, "set message received: " + msg.arg1);

}

} catch (Exception e) {

// Log, don't crash!

Log.e(TAG, "Exception in EneaWorkerHandler.handleMessage:", e);

}

}

}

}

Add to the system server

services/java/com/android/server/SystemServer.Java

try {

Log.i(TAG, "Enea Service");

ServiceManager.addService(Context. ENEA_SERVICE, new EneaService(context));

} catch (Throwable e) {

Log.e(TAG, "Failure starting Enea Service", e);

}

Add a constant value to Context

./core/java/android/content/Context.Java

public static final String ENEA_SERVICE = "enea";

最後

make update-api

make

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved