Android-Adding SystemService

This wiki page will demonstrate - "How to add system service to android framework". Example - "Adding a Bluetooth HID service" - taken as reference of understanding.This will also help to add support for more bluetooth profiles into android framework.

Contents

What is service?

As per the definition given at http://developer.android.com/guide/topics/fundamentals/services.html

A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

Service layer

Create service

  • Add your code to frameworks/base/services/java/com/android/server/
 
 1 /*TestService.java */
 2 package com.android.server;
 3 import android.content.Context;
 4 import android.os.Handler;
 5 import android.os.ITestService;
 6 import android.os.Looper;
 7 import android.os.Message;
 8 import android.os.Process;
 9 import android.util.Log;
10 public class TestService extends ITestService.Stub {
11     private static final String TAG = "TestService";
12     private TestWorkerThread mWorker;
13     private TestWorkerHandler mHandler;
14     private Context mContext;
15     public TestService(Context context) {
16         super();
17         mContext = context;
18         mWorker = new TestWorkerThread("TestServiceWorker");
19         mWorker.start();
20         Log.i(TAG, "Spawned worker thread");
21     }
22
23     public void setValue(int val) {
24         Log.i(TAG, "setValue " + val);
25         Message msg = Message.obtain();
26         msg.what = TestWorkerHandler.MESSAGE_SET;
27         msg.arg1 = val;
28         mHandler.sendMessage(msg);
29     }
30
31     private class TestWorkerThread extends Thread {
32         public TestWorkerThread(String name) {
33             super(name);
34         }
35         public void run() {
36             Looper.prepare();
37             mHandler = new TestWorkerHandler();
38             Looper.loop();
39         }
40     }
41
42     private class TestWorkerHandler extends Handler {
43         private static final int MESSAGE_SET = 0;
44         @Override
45         public void handleMessage(Message msg) {
46             try {
47                 if (msg.what == MESSAGE_SET) {
48                     Log.i(TAG, "set message received: " + msg.arg1);
49                 }
50             } catch (Exception e) {
51                 // Log, don‘t crash!
52                 Log.e(TAG, "Exception in TestWorkerHandler.handleMessage:", e);
53             }
54         }
55     }
56 }

Register service

  • Register service in SystemServer.java
/*
 * go to function "@Override public void run()"
 * ........
 * Add following block after line "if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {"
 */

try {
    Slog.i(TAG, "Test Service");
    ServiceManager.addService(“Test”, new TestService(context));
} catch (Throwable e) {
    Slog.e(TAG, "Failure starting TestService Service", e);
}
 

Expose service

  • A service can expose set of functions that can be access by other process/application. Exposed functions are required to be declared in .aidl file at following location

frameworks/base/core/java/android/os/[server].aidl

/*
* aidl file : frameworks/base/core/java/android/os/ITestService.aidl
* This file contains definitions of functions which are exposed by service
*/
package android.os;
interface ITestService {
/**
* {@hide}
*/
    void setValue(int val);
}

Add [service].aidl for build

/*
 * open frameworks/base/Android.mk and add following line
 */
...
core/java/android/os/IPowerManager.aidl core/java/android/os/ITestService.aidl core/java/android/os/IRemoteCallback.aidl ...
  • Rebuild the framework/base or android system.Service is now ready to use by other application/process.

Using service

To use service

  • first get service handle using "ServiceManager.getService()" api
  • use service handle to call set of functions exposed by service

Below is the sample code to use service.

/*
 * HelloServer.java
 */
package com.Test.helloserver;
import android.app.Activity;
import android.os.Bundle;
import android.os.ServiceManager;
import android.os.ITestService;
import android.util.Log;
public class HelloServer extends Activity {
    private static final String DTAG = "HelloServer";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ITestService om = ITestService.Stub.asInterface(ServiceManager.getService("Test"));
        try {
            Log.d(DTAG, "Going to call service");
            om.setValue(20);
            Log.d(DTAG, "Service called succesfully");
        }
        catch (Exception e) {
            Log.d(DTAG, "FAILED to call service");
            e.printStackTrace();
        }
    }
}
 

References

(from:http://processors.wiki.ti.com/index.php/Android-Adding_SystemService)

Android-Adding SystemService

时间: 2024-08-25 16:03:07

Android-Adding SystemService的相关文章

Android系统服务(SystemService)简介

什么是SystemService 我们在Android开发过程中经常会用到各种各样的系统管理服务,如进行窗口相关的操作会用到窗口管理服务WindowManager,进行电源相关的操作会用到电源管理服务PowerManager,还有很多其他的系统管理服务,如通知管理服务NotifacationManager.振动管理服务Vibrator.电池管理服务BatteryManager-- 这些Manager提供了很多对系统层的控制接口.对于App开发者,只需要了解这些接口的使用方式就可以方便的进行系统控

Android开发学习--Ionic+Cordova 环境搭建

我们看 Ionic 能给我们提供什么?  一个样式库,你可以使用它 来 装饰你的 HTML 网页 ,看起来 想 移动程序的 界面,什么 header .content.footer.grid.list.这貌似没什么 实质性的东西, sencha touch ,jq 都能提供 .一个用 AngularJS 写的 工具库,姑且叫它 组件库吧.Ionic的 grid 设计的比较合理,比 bootstrap的 更强大.当然它 还包含 了angular-animate.angular-resource.a

Android中的系统服务(代理模式)

一,系统启动 Android设备的开机流程总得来分可以分为三部分: 加载引导程序 引导程序bootloader是开机运行的第一个小程序,因此它是针对特定的主板与芯片的.bootloader有很多种,可以使用比较流行的如redboot.uboot.ARMBoot等,也可以开发自己的引导程序,它不是Android操作系统的一部分.引导程序也是OEM厂商或者运营商加锁和限制的地方. 引导程序初始化硬件设备.创建存储器空间的映射等软件运行时所需要的最小环境:加载Linux内核镜像文件(本文只针对Andr

Android 各版本信息 (维基百科)

The following tables show the release dates and key features of all Android operating system updates to date, listed chronologically by their official application programming interface (API) levels. Android 1.0 (API level 1) Android 1.0 (API level 1)

服务 通话录音 TelephonyManager

MainActivity public class MainActivity extends ListActivity {     private BatteryChangedReceiver receiver;     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         List<String> mData 

Cordova 学习步骤

安装环境 [email protected] ~ $ npm install -g cordova npm WARN deprecated [email protected]: use uuid module instead C:\Users\Peng\AppData\Roaming\npm\cordova -> C:\Users\Peng\AppData\Roaming\npm\n ode_modules\cordova\bin\cordova [email protected] C:\Use

安卓Zygote详解

一.Zygote, 意为"受精卵",Android系统中几乎所有的应用进程都是由Zygote进程孵化出来的,Java环境也是由Zygote创建起来的,它建立了我们app运行所需要的环境,是app的祖先,因此,分析它的启动以及内部逻辑显得非常有必要. *Android系统是基于Linux内核的,而在Linux系统中,所有的进程都是init进程的子孙进程,也就是说,所有的进程都是直接或者间接地由init进程fork出来的.Zygote进程也不例外,它是在系统启动的过程,由init进程创建的

cordova(PhoneGap)简单应用

一.先安装node 二.cordova安装,建demo ? ~ git:(master) ? sudo npm install -g cordova Password: /usr/local/bin/cordova -> /usr/local/lib/node_modules/cordova/bin/cordova [email protected] /usr/local/lib/node_modules/cordova ├── [email protected] ├── [email prot

TrustManagerService.java

1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at

Zygote家的大儿子 —— SystemServer

本文基于 Android 9.0 , 代码仓库地址 : android_9.0.0_r45 文中源码链接: SystemServer.java SystemServiceManager.java SystemService.java 首先来回顾一下上篇文章 Java 世界的盘古和女娲 -- Zygote ,主要介绍了 Android 世界中的第一个 Java 进程 Zygote,它的主要工作流程如下: registerServerSocketFromEnv(), 注册服务端 socket,用于和