5

我正在使用aidl自动接听电话,代码如下:

ITelephony.Stub.asInterface(ServiceManager.getService("phone"))
    .answerRingingCall();

我导入 ServiceManager.class

import android.os.ServiceManager;

但是有一个问题:无法解决import android.os.ServiceManager

我怎样才能让它工作?谢谢

4

3 回答 3

6

android.os.ServiceManager是一个隐藏类(即@hide),并且隐藏类(即使它们在 Java 意义上是公共的)从 android.jar 中删除,因此当您尝试导入时会出现错误ServiceManager。隐藏类是 Google 不希望成为文档化公共 API 一部分的那些。

使用非公开 API 的应用程序不容易编译,这个类会有不同的平台版本。

于 2012-02-15T11:28:23.020 回答
2

虽然是旧的,但还没有人回答它。任何隐藏类都可以使用反射 API 来使用。下面是一个通过反射 API 使用 Service Manager 获取服务的示例:

if(mService == null) {
            Method method = null;
            try {
                method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
                IBinder binder = (IBinder) method.invoke(null, "My_SERVICE_NAME");
                if(binder != null) {
                    mService = IMyService.Stub.asInterface(binder);
                }

                if(mService != null)
                    mIsAcquired = true;

            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }

        } else {
            Log.i(TAG, "Service is already acquired");
        }
于 2017-06-26T23:05:17.743 回答
1

如上所述,这些方法仅适用于 Android N 的系统应用程序或框架应用程序。我们仍然可以使用 Android 代码的反射为 System 应用程序编写 ServiceManager 用法,如下所示

  @SuppressLint("PrivateApi")
    public IMyAudioService getService(Context mContext) {
        IMyAudioService mService = null;
        Method method = null;
        try {
            method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
            IBinder binder = (IBinder) method.invoke(null, "YOUR_METHOD_NAME");
            if (binder != null) {
                mService = IMyAudioService .Stub.asInterface(binder);
            }
        } catch (NoSuchMethodException | ClassNotFoundException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return mService;
    }
于 2018-12-16T07:03:39.620 回答