android 源码部分API

android 源码部分API

本文记录博主在阅读android源码过程中底层部分API!

  • sp<Surface> android_view_Surface_getSurface(JNIEnv* env, jobject surfaceObj)

参数:surfaceObj – java对象Surface
返回:java对象Surface有一个long类型的mNativeObject成员,它表示java对象Surface持有Native层Surface的指针,该函数就是返回这个指针

  • ANativeObjectBase类的getSelf函数
    解释:getSelf有多个重载函数,函数都是将参数类型强转为返回值类型,其中一个源码如下:
    static inline TYPE* getSelf(NATIVE_TYPE* self) {
    
    
        return static_cast<TYPE*>(self);
    }
  • jobject jniCreateFileDescriptor(C_JNIEnv* env, int fd)
    为这个fd文件描述符,创建一个FileDescriptor的java包裹类;也就是new FileDescriptor类,为其descriptor成员设置值fd,该方法用处通常用来保存native层打开的一些属性唯一值,如c++的socket返回值;
jobject jniCreateFileDescriptor(C_JNIEnv* env, int fd) {
    
    
    JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
    JniConstants::init(e);
    <init>也就是java的构造方法,()V是方法签名,JniConstants::fileDescriptorClass是一个字符串
    “java/io/FileDescriptor”
    static jmethodID ctor = e->GetMethodID(JniConstants::fileDescriptorClass, "<init>", "()V");
    jobject fileDescriptor = (*env)->NewObject(e, JniConstants::fileDescriptorClass, ctor);
    // NOTE: NewObject ensures that an OutOfMemoryError will be seen by the Java
    // caller if the alloc fails, so we just return NULL when that happens.
    if (fileDescriptor != NULL)  {
    
    
    	//设置成员descriptor值为fd
        jniSetFileDescriptorOfFD(env, fileDescriptor, fd);
    }
    return fileDescriptor;
}

如何重启系统

调用电源管理模块Binder服务reboot即可

void rebootSystem(String reason) {
    
                                                                                                                                                                                                                                                   
   Slog.i(TAG, "Rebooting system because: " + reason);
    IPowerManager pms = (IPowerManager)ServiceManager.getService(Context.POWER_SERVICE);
    try {
    
    
        pms.reboot(false, reason, false);
    } catch (RemoteException ex) {
    
    
   }
}

获取系统服务为什么强转没有出错

如下代码:

SearchManager seach = (SearchManager)context.getSystemService(Context.SEARCH_SERVICE);

为什么强转没事?是因为提前存储好了,存储在哪个地方呢?在SystemServiceRegistry类里面的静态代码块里面,如下格式代码:

static {
    
    
registerService(Context.SEARCH_SERVICE, SearchManager.class,                                                                                                                                                                                                                     
       new CachedServiceFetcher<SearchManager>() {
    
    
   @Override
   public SearchManager createService(ContextImpl ctx) throws ServiceNotFoundException {
    
    
       return new SearchManager(ctx.getOuterContext(),
               ctx.mMainThread.getHandler());
   }});
}
注册服务
private static <T> void registerService(String serviceName, Class<T> serviceClass,                                                                                                                                                                                                   
        ServiceFetcher<T> serviceFetcher) {
    
    
    以下是Map格式    
    SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
    以下也是Map格式,value是Fetcher,用于创建具体的服务,当然这个服务知识Binder客户端,不是服务端
    SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
}

启动系统服务之反射

当我们在写系统服务时,通常会看到这样的代码:

这是一个aidl服务
public class SearchManagerService extends ISearchManager.Stub {
    
    
	内部类Lifecycle继承SystemService
    public static class Lifecycle extends SystemService {
    
    
        private SearchManagerService mService;
        public Lifecycle(Context context) {
    
    
            super(context);
        }   

        @Override
        public void onStart() {
    
    
        	创建自己的服务
            mService = new SearchManagerService(getContext());
            调用SystemService方法,实质就是将服务加入到Binder服务列表中去
            publishBinderService(Context.SEARCH_SERVICE, mService);
        }   
    }
}

所以从上所知,只需要调用onStart方法就可以启动我们的服务了;那在哪个地方调用了onStart方法呢?
答案就在SystemServer中,请看下面代码:

声明了SearchManagerService的内部类Lifecycle
private static final String SEARCH_MANAGER_SERVICE_CLASS =                                                                                                                                                                                                                           
            "com.android.server.search.SearchManagerService$Lifecycle";
mSystemServiceManager类型就是SystemServiceManager            
mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS); 

我们去看看SystemServiceManager里面的startService方法:

public SystemService startService(String className) {
    
    
  final Class<SystemService> serviceClass;
  try {
    
    
  		反射获取类Lifecycle
      serviceClass = (Class<SystemService>)Class.forName(className);
  } catch (ClassNotFoundException ex) {
    
    
      Slog.i(TAG, "Starting " + className);
      throw new RuntimeException("Failed to create service " + className
              + ": service class not found, usually indicates that the caller should "
              + "have called PackageManager.hasSystemFeature() to check whether the "
              + "feature is available on this device before trying to start the "
              + "services that implement it", ex);
  }
  return startService(serviceClass);
}

 public <T extends SystemService> T startService(Class<T> serviceClass) {
    
    
        try {
    
    
            final String name = serviceClass.getName();
           ...

            // Create the service.
            if (!SystemService.class.isAssignableFrom(serviceClass)) {
    
    
                throw new RuntimeException("Failed to create " + name
                        + ": service must extend " + SystemService.class.getName());
            }
            final T service;
           ....获取类的构造方法并调用构造方法创建Lifecycle的对象
                Constructor<T> constructor = serviceClass.getConstructor(Context.class);
                service = constructor.newInstance(mContext);
          ....
		再次调用重载函数
            startService(service);
            return service;
        } finally {
    
    
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
    }
 public void startService(@NonNull final SystemService service) {
    
    
        // Register it.
        mServices.add(service);
        // Start it.
        long time = System.currentTimeMillis();
        try {
    
    
        调用Service的onstart方法,也就是最开始SearchManagerService的内部类Lifecycle的onStart方法
            service.onStart();
        } catch (RuntimeException ex) {
    
    
            throw new RuntimeException("Failed to start service " + service.getClass().getName()
                    + ": onStart threw an exception", ex);
        }
        warnIfTooLong(System.currentTimeMillis() - time, service, "onStart");
    }

猜你喜欢

转载自blog.csdn.net/jackzhouyu/article/details/107142999