Context error of custom system service

2019-08-05 10:05发布

问题:

I have created a system service that communicates with a zigbee device. Updated APIs and created system.img and flashed on the device and made custom SDK for android programming.

In the Mainactivity class,

try {
        ZigbeeManager zm = (ZigbeeManager) getSystemService(Context.ZIGBEE_SERVICE);
        zm.write("Hello World!\r");
    } catch (Exception ex) {
        Log.d(TAG, "Error in Zigbee Service: " + ex.toString());
    }

I am getting an error over the words "Context.ZIGBEE_SERVICE". It says "Must be one of : list of all system services" when I put my cursor over it. Using other system services works. Also Zigbee Service is available in the Context.class file just like the other system services.

...
public static final String WIFI_SERVICE = "wifi";
public static final String WINDOW_SERVICE = "window";
public static final String ZIGBEE_SERVICE = "zigbee";

Now when running it on the device. I get this error message on the logcat.

01-01 12:09:24.126 6874-6874/com.jcxmej.uartcontrol D/UARTControl: Error in Zigbee Service: java.lang.NullPointerException: Attempt to invoke interface method 'int android.os.IZigbeeService.write(java.lang.String)' on a null object reference

The object is Null. Does it need to be intialised but how? But I think it is Null because the context is not linked properly. How do I get rid of the Context error. Or properly add Zigbee service in the Context.

I used this as reference. https://github.com/nayobix/add-new-hardware-hal-android-5-lollipop

回答1:

When register a system service inside the framework (Assuming you already built the service) you need to do more than add the String name of your service, you need to perform the next steps:

  1. Register your service in SystemServer.java (Dig to the code and add it to the try/catch List of all services).
  2. Add your AIDL to frameworks/base/core/java/android/os/.
  3. Add your serivce file name to the build inside frameworks/base/Android.mk .

You can see more info in this great article.