转自:http://blog.csdn.net/jacklam200/article/details/37567409

跟上篇Binder使用一样,先通过例子来跟踪Java层Binder机制。本文参考了Binder In java

(http://www.cnblogs.com/angeldevil/p/3328748.html),只作为研究Android记忆用

在Init进程的init2阶段,系统启动了ServerThread,在ServerThread中会启动很多用Java实现的系统服务

(frameworks/base/services/java/com/android/server/SystemServer.java)

代码

[java] view plaincopy
  1. power = new PowerManagerService();
  2. ServiceManager.addService(Context.POWER_SERVICE, power);
  3. context = ActivityManagerService.main(factoryTest);
  4. Slog.i(TAG, "Display Manager");
  5. display = new DisplayManagerService(context, wmHandler, uiHandler);
  6. ServiceManager.addService(Context.DISPLAY_SERVICE, display, true);

通过ServiceManager的addService注册为binder 的server端。

我们以PowerManagerService为例,

(frameworks/base/services/java/com/android/server/power/)

PowerManagerService继承于IPowerManager.stub,而IPowerManager.stub位于

(frameworks/base/core/java/com/android/os/IPowerManager.aidl)

[java] view plaincopy
  1. package android.os;
  2. import android.os.WorkSource;
  3. /** @hide */
  4. interface IPowerManager
  5. {
  6. // WARNING: The first two methods must remain the first two methods because their
  7. // transaction numbers must not change unless IPowerManager.cpp is also updated.
  8. void acquireWakeLock(IBinder lock, int flags, String tag, in WorkSource ws);
  9. void releaseWakeLock(IBinder lock, int flags);
  10. void updateWakeLockWorkSource(IBinder lock, in WorkSource ws);
  11. boolean isWakeLockLevelSupported(int level);
  12. void userActivity(long time, int event, int flags);
  13. void wakeUp(long time);
  14. void goToSleep(long time, int reason);
  15. void nap(long time);
  16. boolean isScreenOn();
  17. void reboot(boolean confirm, String reason, boolean wait);
  18. void shutdown(boolean confirm, boolean wait);
  19. void crash(String message);
  20. void setStayOnSetting(int val);
  21. void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs);
  22. // temporarily overrides the screen brightness settings to allow the user to
  23. // see the effect of a settings change without applying it immediately
  24. void setTemporaryScreenBrightnessSettingOverride(int brightness);
  25. void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj);
  26. // sets the attention light (used by phone app only)
  27. void setAttentionLight(boolean on, int color);
  28. }

Aidl是android内部进程通信接口的描述语言,通过编译我们可以编译出

[java] view plaincopy
  1. package android.os;
  2. /** @hide */
  3. public interface IPowerManager extends android.os.IInterface {
  4. /** Local-side IPC implementation stub class. */
  5. public static abstract class Stub extends android.os.Binder implements
  6. android.os.IPowerManager {
  7. private static final java.lang.String DESCRIPTOR = "android.os.IPowerManager";
  8. /** Construct the stub at attach it to the interface. */
  9. public Stub() {
  10. this.attachInterface(this, DESCRIPTOR);
  11. }
  12. /**
  13. * Cast an IBinder object into an android.os.IPowerManager interface,
  14. * generating a proxy if needed.
  15. */
  16. public static android.os.IPowerManager asInterface(
  17. android.os.IBinder obj) {
  18. if ((obj == null)) {
  19. return null;
  20. }
  21. android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
  22. if (((iin != null) && (iin instanceof android.os.IPowerManager))) {
  23. return ((android.os.IPowerManager) iin);
  24. }
  25. return new android.os.IPowerManager.Stub.Proxy(obj);
  26. }
  27. @Override
  28. public android.os.IBinder asBinder() {
  29. return this;
  30. }
  31. @Override
  32. public boolean onTransact(int code, android.os.Parcel data,
  33. android.os.Parcel reply, int flags)
  34. throws android.os.RemoteException {
  35. switch (code) {
  36. case INTERFACE_TRANSACTION: {
  37. reply.writeString(DESCRIPTOR);
  38. return true;
  39. }
  40. case TRANSACTION_acquireWakeLock: {
  41. data.enforceInterface(DESCRIPTOR);
  42. android.os.IBinder _arg0;
  43. _arg0 = data.readStrongBinder();
  44. int _arg1;
  45. _arg1 = data.readInt();
  46. java.lang.String _arg2;
  47. _arg2 = data.readString();
  48. android.os.WorkSource _arg3;
  49. if ((0 != data.readInt())) {
  50. _arg3 = android.os.WorkSource.CREATOR
  51. .createFromParcel(data);
  52. } else {
  53. _arg3 = null;
  54. }
  55. this.acquireWakeLock(_arg0, _arg1, _arg2, _arg3);
  56. reply.writeNoException();
  57. return true;
  58. }
  59. case TRANSACTION_releaseWakeLock: {
  60. data.enforceInterface(DESCRIPTOR);
  61. android.os.IBinder _arg0;
  62. _arg0 = data.readStrongBinder();
  63. int _arg1;
  64. _arg1 = data.readInt();
  65. this.releaseWakeLock(_arg0, _arg1);
  66. reply.writeNoException();
  67. return true;
  68. }
  69. case TRANSACTION_updateWakeLockWorkSource: {
  70. data.enforceInterface(DESCRIPTOR);
  71. android.os.IBinder _arg0;
  72. _arg0 = data.readStrongBinder();
  73. android.os.WorkSource _arg1;
  74. if ((0 != data.readInt())) {
  75. _arg1 = android.os.WorkSource.CREATOR
  76. .createFromParcel(data);
  77. } else {
  78. _arg1 = null;
  79. }
  80. this.updateWakeLockWorkSource(_arg0, _arg1);
  81. reply.writeNoException();
  82. return true;
  83. }
  84. case TRANSACTION_isWakeLockLevelSupported: {
  85. data.enforceInterface(DESCRIPTOR);
  86. int _arg0;
  87. _arg0 = data.readInt();
  88. boolean _result = this.isWakeLockLevelSupported(_arg0);
  89. reply.writeNoException();
  90. reply.writeInt(((_result) ? (1) : (0)));
  91. return true;
  92. }
  93. case TRANSACTION_userActivity: {
  94. data.enforceInterface(DESCRIPTOR);
  95. long _arg0;
  96. _arg0 = data.readLong();
  97. int _arg1;
  98. _arg1 = data.readInt();
  99. int _arg2;
  100. _arg2 = data.readInt();
  101. this.userActivity(_arg0, _arg1, _arg2);
  102. reply.writeNoException();
  103. return true;
  104. }
  105. case TRANSACTION_wakeUp: {
  106. data.enforceInterface(DESCRIPTOR);
  107. long _arg0;
  108. _arg0 = data.readLong();
  109. this.wakeUp(_arg0);
  110. reply.writeNoException();
  111. return true;
  112. }
  113. case TRANSACTION_goToSleep: {
  114. data.enforceInterface(DESCRIPTOR);
  115. long _arg0;
  116. _arg0 = data.readLong();
  117. int _arg1;
  118. _arg1 = data.readInt();
  119. this.goToSleep(_arg0, _arg1);
  120. reply.writeNoException();
  121. return true;
  122. }
  123. case TRANSACTION_nap: {
  124. data.enforceInterface(DESCRIPTOR);
  125. long _arg0;
  126. _arg0 = data.readLong();
  127. this.nap(_arg0);
  128. reply.writeNoException();
  129. return true;
  130. }
  131. case TRANSACTION_isScreenOn: {
  132. data.enforceInterface(DESCRIPTOR);
  133. boolean _result = this.isScreenOn();
  134. reply.writeNoException();
  135. reply.writeInt(((_result) ? (1) : (0)));
  136. return true;
  137. }
  138. case TRANSACTION_reboot: {
  139. data.enforceInterface(DESCRIPTOR);
  140. boolean _arg0;
  141. _arg0 = (0 != data.readInt());
  142. java.lang.String _arg1;
  143. _arg1 = data.readString();
  144. boolean _arg2;
  145. _arg2 = (0 != data.readInt());
  146. this.reboot(_arg0, _arg1, _arg2);
  147. reply.writeNoException();
  148. return true;
  149. }
  150. case TRANSACTION_shutdown: {
  151. data.enforceInterface(DESCRIPTOR);
  152. boolean _arg0;
  153. _arg0 = (0 != data.readInt());
  154. boolean _arg1;
  155. _arg1 = (0 != data.readInt());
  156. this.shutdown(_arg0, _arg1);
  157. reply.writeNoException();
  158. return true;
  159. }
  160. case TRANSACTION_crash: {
  161. data.enforceInterface(DESCRIPTOR);
  162. java.lang.String _arg0;
  163. _arg0 = data.readString();
  164. this.crash(_arg0);
  165. reply.writeNoException();
  166. return true;
  167. }
  168. case TRANSACTION_setStayOnSetting: {
  169. data.enforceInterface(DESCRIPTOR);
  170. int _arg0;
  171. _arg0 = data.readInt();
  172. this.setStayOnSetting(_arg0);
  173. reply.writeNoException();
  174. return true;
  175. }
  176. case TRANSACTION_setMaximumScreenOffTimeoutFromDeviceAdmin: {
  177. data.enforceInterface(DESCRIPTOR);
  178. int _arg0;
  179. _arg0 = data.readInt();
  180. this.setMaximumScreenOffTimeoutFromDeviceAdmin(_arg0);
  181. reply.writeNoException();
  182. return true;
  183. }
  184. case TRANSACTION_setTemporaryScreenBrightnessSettingOverride: {
  185. data.enforceInterface(DESCRIPTOR);
  186. int _arg0;
  187. _arg0 = data.readInt();
  188. this.setTemporaryScreenBrightnessSettingOverride(_arg0);
  189. reply.writeNoException();
  190. return true;
  191. }
  192. case TRANSACTION_setTemporaryScreenAutoBrightnessAdjustmentSettingOverride: {
  193. data.enforceInterface(DESCRIPTOR);
  194. float _arg0;
  195. _arg0 = data.readFloat();
  196. this.setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(_arg0);
  197. reply.writeNoException();
  198. return true;
  199. }
  200. case TRANSACTION_setAttentionLight: {
  201. data.enforceInterface(DESCRIPTOR);
  202. boolean _arg0;
  203. _arg0 = (0 != data.readInt());
  204. int _arg1;
  205. _arg1 = data.readInt();
  206. this.setAttentionLight(_arg0, _arg1);
  207. reply.writeNoException();
  208. return true;
  209. }
  210. }
  211. return super.onTransact(code, data, reply, flags);
  212. }
  213. private static class Proxy implements android.os.IPowerManager {
  214. private android.os.IBinder mRemote;
  215. Proxy(android.os.IBinder remote) {
  216. mRemote = remote;
  217. }
  218. @Override
  219. public android.os.IBinder asBinder() {
  220. return mRemote;
  221. }
  222. public java.lang.String getInterfaceDescriptor() {
  223. return DESCRIPTOR;
  224. }
  225. // WARNING: The first two methods must remain the first two methods
  226. // because their
  227. // transaction numbers must not change unless IPowerManager.cpp is
  228. // also updated.
  229. @Override
  230. public void acquireWakeLock(android.os.IBinder lock, int flags,
  231. java.lang.String tag, android.os.WorkSource ws)
  232. throws android.os.RemoteException {
  233. android.os.Parcel _data = android.os.Parcel.obtain();
  234. android.os.Parcel _reply = android.os.Parcel.obtain();
  235. try {
  236. _data.writeInterfaceToken(DESCRIPTOR);
  237. _data.writeStrongBinder(lock);
  238. _data.writeInt(flags);
  239. _data.writeString(tag);
  240. if ((ws != null)) {
  241. _data.writeInt(1);
  242. ws.writeToParcel(_data, 0);
  243. } else {
  244. _data.writeInt(0);
  245. }
  246. mRemote.transact(Stub.TRANSACTION_acquireWakeLock, _data,
  247. _reply, 0);
  248. _reply.readException();
  249. } finally {
  250. _reply.recycle();
  251. _data.recycle();
  252. }
  253. }
  254. @Override
  255. public void releaseWakeLock(android.os.IBinder lock, int flags)
  256. throws android.os.RemoteException {
  257. android.os.Parcel _data = android.os.Parcel.obtain();
  258. android.os.Parcel _reply = android.os.Parcel.obtain();
  259. try {
  260. _data.writeInterfaceToken(DESCRIPTOR);
  261. _data.writeStrongBinder(lock);
  262. _data.writeInt(flags);
  263. mRemote.transact(Stub.TRANSACTION_releaseWakeLock, _data,
  264. _reply, 0);
  265. _reply.readException();
  266. } finally {
  267. _reply.recycle();
  268. _data.recycle();
  269. }
  270. }
  271. @Override
  272. public void updateWakeLockWorkSource(android.os.IBinder lock,
  273. android.os.WorkSource ws) throws android.os.RemoteException {
  274. android.os.Parcel _data = android.os.Parcel.obtain();
  275. android.os.Parcel _reply = android.os.Parcel.obtain();
  276. try {
  277. _data.writeInterfaceToken(DESCRIPTOR);
  278. _data.writeStrongBinder(lock);
  279. if ((ws != null)) {
  280. _data.writeInt(1);
  281. ws.writeToParcel(_data, 0);
  282. } else {
  283. _data.writeInt(0);
  284. }
  285. mRemote.transact(Stub.TRANSACTION_updateWakeLockWorkSource,
  286. _data, _reply, 0);
  287. _reply.readException();
  288. } finally {
  289. _reply.recycle();
  290. _data.recycle();
  291. }
  292. }
  293. @Override
  294. public boolean isWakeLockLevelSupported(int level)
  295. throws android.os.RemoteException {
  296. android.os.Parcel _data = android.os.Parcel.obtain();
  297. android.os.Parcel _reply = android.os.Parcel.obtain();
  298. boolean _result;
  299. try {
  300. _data.writeInterfaceToken(DESCRIPTOR);
  301. _data.writeInt(level);
  302. mRemote.transact(Stub.TRANSACTION_isWakeLockLevelSupported,
  303. _data, _reply, 0);
  304. _reply.readException();
  305. _result = (0 != _reply.readInt());
  306. } finally {
  307. _reply.recycle();
  308. _data.recycle();
  309. }
  310. return _result;
  311. }
  312. @Override
  313. public void userActivity(long time, int event, int flags)
  314. throws android.os.RemoteException {
  315. android.os.Parcel _data = android.os.Parcel.obtain();
  316. android.os.Parcel _reply = android.os.Parcel.obtain();
  317. try {
  318. _data.writeInterfaceToken(DESCRIPTOR);
  319. _data.writeLong(time);
  320. _data.writeInt(event);
  321. _data.writeInt(flags);
  322. mRemote.transact(Stub.TRANSACTION_userActivity, _data,
  323. _reply, 0);
  324. _reply.readException();
  325. } finally {
  326. _reply.recycle();
  327. _data.recycle();
  328. }
  329. }
  330. @Override
  331. public void wakeUp(long time) throws android.os.RemoteException {
  332. android.os.Parcel _data = android.os.Parcel.obtain();
  333. android.os.Parcel _reply = android.os.Parcel.obtain();
  334. try {
  335. _data.writeInterfaceToken(DESCRIPTOR);
  336. _data.writeLong(time);
  337. mRemote.transact(Stub.TRANSACTION_wakeUp, _data, _reply, 0);
  338. _reply.readException();
  339. } finally {
  340. _reply.recycle();
  341. _data.recycle();
  342. }
  343. }
  344. @Override
  345. public void goToSleep(long time, int reason)
  346. throws android.os.RemoteException {
  347. android.os.Parcel _data = android.os.Parcel.obtain();
  348. android.os.Parcel _reply = android.os.Parcel.obtain();
  349. try {
  350. _data.writeInterfaceToken(DESCRIPTOR);
  351. _data.writeLong(time);
  352. _data.writeInt(reason);
  353. mRemote.transact(Stub.TRANSACTION_goToSleep, _data, _reply,
  354. 0);
  355. _reply.readException();
  356. } finally {
  357. _reply.recycle();
  358. _data.recycle();
  359. }
  360. }
  361. @Override
  362. public void nap(long time) throws android.os.RemoteException {
  363. android.os.Parcel _data = android.os.Parcel.obtain();
  364. android.os.Parcel _reply = android.os.Parcel.obtain();
  365. try {
  366. _data.writeInterfaceToken(DESCRIPTOR);
  367. _data.writeLong(time);
  368. mRemote.transact(Stub.TRANSACTION_nap, _data, _reply, 0);
  369. _reply.readException();
  370. } finally {
  371. _reply.recycle();
  372. _data.recycle();
  373. }
  374. }
  375. @Override
  376. public boolean isScreenOn() throws android.os.RemoteException {
  377. android.os.Parcel _data = android.os.Parcel.obtain();
  378. android.os.Parcel _reply = android.os.Parcel.obtain();
  379. boolean _result;
  380. try {
  381. _data.writeInterfaceToken(DESCRIPTOR);
  382. mRemote.transact(Stub.TRANSACTION_isScreenOn, _data,
  383. _reply, 0);
  384. _reply.readException();
  385. _result = (0 != _reply.readInt());
  386. } finally {
  387. _reply.recycle();
  388. _data.recycle();
  389. }
  390. return _result;
  391. }
  392. @Override
  393. public void reboot(boolean confirm, java.lang.String reason,
  394. boolean wait) throws android.os.RemoteException {
  395. android.os.Parcel _data = android.os.Parcel.obtain();
  396. android.os.Parcel _reply = android.os.Parcel.obtain();
  397. try {
  398. _data.writeInterfaceToken(DESCRIPTOR);
  399. _data.writeInt(((confirm) ? (1) : (0)));
  400. _data.writeString(reason);
  401. _data.writeInt(((wait) ? (1) : (0)));
  402. mRemote.transact(Stub.TRANSACTION_reboot, _data, _reply, 0);
  403. _reply.readException();
  404. } finally {
  405. _reply.recycle();
  406. _data.recycle();
  407. }
  408. }
  409. @Override
  410. public void shutdown(boolean confirm, boolean wait)
  411. throws android.os.RemoteException {
  412. android.os.Parcel _data = android.os.Parcel.obtain();
  413. android.os.Parcel _reply = android.os.Parcel.obtain();
  414. try {
  415. _data.writeInterfaceToken(DESCRIPTOR);
  416. _data.writeInt(((confirm) ? (1) : (0)));
  417. _data.writeInt(((wait) ? (1) : (0)));
  418. mRemote.transact(Stub.TRANSACTION_shutdown, _data, _reply,
  419. 0);
  420. _reply.readException();
  421. } finally {
  422. _reply.recycle();
  423. _data.recycle();
  424. }
  425. }
  426. @Override
  427. public void crash(java.lang.String message)
  428. throws android.os.RemoteException {
  429. android.os.Parcel _data = android.os.Parcel.obtain();
  430. android.os.Parcel _reply = android.os.Parcel.obtain();
  431. try {
  432. _data.writeInterfaceToken(DESCRIPTOR);
  433. _data.writeString(message);
  434. mRemote.transact(Stub.TRANSACTION_crash, _data, _reply, 0);
  435. _reply.readException();
  436. } finally {
  437. _reply.recycle();
  438. _data.recycle();
  439. }
  440. }
  441. @Override
  442. public void setStayOnSetting(int val)
  443. throws android.os.RemoteException {
  444. android.os.Parcel _data = android.os.Parcel.obtain();
  445. android.os.Parcel _reply = android.os.Parcel.obtain();
  446. try {
  447. _data.writeInterfaceToken(DESCRIPTOR);
  448. _data.writeInt(val);
  449. mRemote.transact(Stub.TRANSACTION_setStayOnSetting, _data,
  450. _reply, 0);
  451. _reply.readException();
  452. } finally {
  453. _reply.recycle();
  454. _data.recycle();
  455. }
  456. }
  457. @Override
  458. public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs)
  459. throws android.os.RemoteException {
  460. android.os.Parcel _data = android.os.Parcel.obtain();
  461. android.os.Parcel _reply = android.os.Parcel.obtain();
  462. try {
  463. _data.writeInterfaceToken(DESCRIPTOR);
  464. _data.writeInt(timeMs);
  465. mRemote.transact(
  466. Stub.TRANSACTION_setMaximumScreenOffTimeoutFromDeviceAdmin,
  467. _data, _reply, 0);
  468. _reply.readException();
  469. } finally {
  470. _reply.recycle();
  471. _data.recycle();
  472. }
  473. }
  474. // temporarily overrides the screen brightness settings to allow the
  475. // user to
  476. // see the effect of a settings change without applying it
  477. // immediately
  478. @Override
  479. public void setTemporaryScreenBrightnessSettingOverride(
  480. int brightness) throws android.os.RemoteException {
  481. android.os.Parcel _data = android.os.Parcel.obtain();
  482. android.os.Parcel _reply = android.os.Parcel.obtain();
  483. try {
  484. _data.writeInterfaceToken(DESCRIPTOR);
  485. _data.writeInt(brightness);
  486. mRemote.transact(
  487. Stub.TRANSACTION_setTemporaryScreenBrightnessSettingOverride,
  488. _data, _reply, 0);
  489. _reply.readException();
  490. } finally {
  491. _reply.recycle();
  492. _data.recycle();
  493. }
  494. }
  495. @Override
  496. public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(
  497. float adj) throws android.os.RemoteException {
  498. android.os.Parcel _data = android.os.Parcel.obtain();
  499. android.os.Parcel _reply = android.os.Parcel.obtain();
  500. try {
  501. _data.writeInterfaceToken(DESCRIPTOR);
  502. _data.writeFloat(adj);
  503. mRemote.transact(
  504. Stub.TRANSACTION_setTemporaryScreenAutoBrightnessAdjustmentSettingOverride,
  505. _data, _reply, 0);
  506. _reply.readException();
  507. } finally {
  508. _reply.recycle();
  509. _data.recycle();
  510. }
  511. }
  512. // sets the attention light (used by phone app only)
  513. @Override
  514. public void setAttentionLight(boolean on, int color)
  515. throws android.os.RemoteException {
  516. android.os.Parcel _data = android.os.Parcel.obtain();
  517. android.os.Parcel _reply = android.os.Parcel.obtain();
  518. try {
  519. _data.writeInterfaceToken(DESCRIPTOR);
  520. _data.writeInt(((on) ? (1) : (0)));
  521. _data.writeInt(color);
  522. mRemote.transact(Stub.TRANSACTION_setAttentionLight, _data,
  523. _reply, 0);
  524. _reply.readException();
  525. } finally {
  526. _reply.recycle();
  527. _data.recycle();
  528. }
  529. }
  530. }
  531. static final int TRANSACTION_acquireWakeLock = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
  532. static final int TRANSACTION_releaseWakeLock = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
  533. static final int TRANSACTION_updateWakeLockWorkSource = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2);
  534. static final int TRANSACTION_isWakeLockLevelSupported = (android.os.IBinder.FIRST_CALL_TRANSACTION + 3);
  535. static final int TRANSACTION_userActivity = (android.os.IBinder.FIRST_CALL_TRANSACTION + 4);
  536. static final int TRANSACTION_wakeUp = (android.os.IBinder.FIRST_CALL_TRANSACTION + 5);
  537. static final int TRANSACTION_goToSleep = (android.os.IBinder.FIRST_CALL_TRANSACTION + 6);
  538. static final int TRANSACTION_nap = (android.os.IBinder.FIRST_CALL_TRANSACTION + 7);
  539. static final int TRANSACTION_isScreenOn = (android.os.IBinder.FIRST_CALL_TRANSACTION + 8);
  540. static final int TRANSACTION_reboot = (android.os.IBinder.FIRST_CALL_TRANSACTION + 9);
  541. static final int TRANSACTION_shutdown = (android.os.IBinder.FIRST_CALL_TRANSACTION + 10);
  542. static final int TRANSACTION_crash = (android.os.IBinder.FIRST_CALL_TRANSACTION + 11);
  543. static final int TRANSACTION_setStayOnSetting = (android.os.IBinder.FIRST_CALL_TRANSACTION + 12);
  544. static final int TRANSACTION_setMaximumScreenOffTimeoutFromDeviceAdmin = (android.os.IBinder.FIRST_CALL_TRANSACTION + 13);
  545. static final int TRANSACTION_setTemporaryScreenBrightnessSettingOverride = (android.os.IBinder.FIRST_CALL_TRANSACTION + 14);
  546. static final int TRANSACTION_setTemporaryScreenAutoBrightnessAdjustmentSettingOverride = (android.os.IBinder.FIRST_CALL_TRANSACTION + 15);
  547. static final int TRANSACTION_setAttentionLight = (android.os.IBinder.FIRST_CALL_TRANSACTION + 16);
  548. }
  549. // WARNING: The first two methods must remain the first two methods because
  550. // their
  551. // transaction numbers must not change unless IPowerManager.cpp is also
  552. // updated.
  553. public void acquireWakeLock(android.os.IBinder lock, int flags,
  554. java.lang.String tag, android.os.WorkSource ws)
  555. throws android.os.RemoteException;
  556. public void releaseWakeLock(android.os.IBinder lock, int flags)
  557. throws android.os.RemoteException;
  558. public void updateWakeLockWorkSource(android.os.IBinder lock,
  559. android.os.WorkSource ws) throws android.os.RemoteException;
  560. public boolean isWakeLockLevelSupported(int level)
  561. throws android.os.RemoteException;
  562. public void userActivity(long time, int event, int flags)
  563. throws android.os.RemoteException;
  564. public void wakeUp(long time) throws android.os.RemoteException;
  565. public void goToSleep(long time, int reason)
  566. throws android.os.RemoteException;
  567. public void nap(long time) throws android.os.RemoteException;
  568. public boolean isScreenOn() throws android.os.RemoteException;
  569. public void reboot(boolean confirm, java.lang.String reason, boolean wait)
  570. throws android.os.RemoteException;
  571. public void shutdown(boolean confirm, boolean wait)
  572. throws android.os.RemoteException;
  573. public void crash(java.lang.String message)
  574. throws android.os.RemoteException;
  575. public void setStayOnSetting(int val) throws android.os.RemoteException;
  576. public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs)
  577. throws android.os.RemoteException;
  578. // temporarily overrides the screen brightness settings to allow the user to
  579. // see the effect of a settings change without applying it immediately
  580. public void setTemporaryScreenBrightnessSettingOverride(int brightness)
  581. throws android.os.RemoteException;
  582. public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(
  583. float adj) throws android.os.RemoteException;
  584. // sets the attention light (used by phone app only)
  585. public void setAttentionLight(boolean on, int color)
  586. throws android.os.RemoteException;
  587. }

我们可以从代码中看到Stub是一个抽象类,里面还有个proxy类

Stub提供asInterface, asBinder, onTransact,

PowerManagerService

其实这个是不是看起来很熟悉呢,我们回忆下MediaplayerService,MediaplayerService 继承于BnMediaPlayerService,而BnMediaPlayerService刚好跟这个Stub很类似,

然后我们再看看proxy类是不是跟BpMediaPlayerService类似,而IPowerManager则跟IMediaPlayerService类似,而PowerManagerServic则跟MediaplayerService一样实现功能。

并Stub继承于Binder,而在Binder构造函数中调用native的init

(framework\base\core\jni\android_util_Binder.cpp)

[cpp] view plaincopy
  1. static void android_os_Binder_init(JNIEnv* env, jobject obj)
  2. {
  3. JavaBBinderHolder* jbh = new JavaBBinderHolder();
  4. if (jbh == NULL) {
  5. jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
  6. return;
  7. }
  8. ALOGV("Java Binder %p: acquiring first ref on holder %p", obj, jbh);
  9. jbh->incStrong((void*)android_os_Binder_init);
  10. env->SetIntField(obj, gBinderOffsets.mObject, (int)jbh);
  11. }

可以看出创建了一个JavaBBinderHolder,然后把值强制转int,返回给java层Binder类的

[java] view plaincopy
  1. private int mObject;
[cpp] view plaincopy
  1. </pre><p class="p0" style="margin-bottom:0pt; margin-top:0pt"><span style="font-size:10pt; font-family:宋体">在<span style="font-family:Consolas">AndroidRuntine::startReg</span><span style="font-family:宋体">中会调用</span><span style="font-family:Consolas">register_android_os_Binder</span><span style="font-family:宋体">,</span><span style="font-family:Consolas">register_android_os_Binder</span><span style="font-family:宋体">会调用</span><span style="font-family:Consolas">int_register_android_os_Binder</span><span style="font-family:宋体">等函数建立</span><span style="font-family:Consolas">Java</span><span style="font-family:宋体">层</span><span style="font-family:Consolas">Binder</span><span style="font-family:宋体">、</span><span style="font-family:Consolas">BinderProxy</span><span style="font-family:宋体">、</span><span style="font-family:Consolas">BinderInternal</span><span style="font-family:宋体">、</span><span style="font-family:Consolas">Log</span><span style="font-family:宋体">等与</span><span style="font-family:Consolas">Native</span><span style="font-family:宋体">层的映射关系</span></span><span style="font-size:10pt; font-family:宋体"></span></p><p class="p0" style="margin-bottom:0pt; margin-top:0pt"><span style="font-size:10pt; font-family:宋体">Native<span style="font-family:宋体">层对</span><span style="font-family:Consolas">java</span><span style="font-family:宋体">层的反射</span></span><span style="font-size:10pt; font-family:宋体"></span></p><pre code_snippet_id="422453" snippet_file_name="blog_20140708_7_4207713" name="code" class="cpp">static int int_register_android_os_Binder(JNIEnv* env)
  2. {
  3. jclass clazz;
  4. clazz = env->FindClass(kBinderPathName);
  5. LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.Binder");
  6. gBinderOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
  7. gBinderOffsets.mExecTransact
  8. = env->GetMethodID(clazz, "execTransact", "(IIII)Z");
  9. assert(gBinderOffsets.mExecTransact);
  10. gBinderOffsets.mObject
  11. = env->GetFieldID(clazz, "mObject", "I");
  12. assert(gBinderOffsets.mObject);
  13. return AndroidRuntime::registerNativeMethods(
  14. env, kBinderPathName,
  15. gBinderMethods, NELEM(gBinderMethods));
  16. }

那JavaBBinderHolder是什么呢?

在android_os_Binder_init中new了一个JavaBBinderHolder,JavaBBinderHolder 的get()函数new了一个JavaBBinder保存到了自己的成员sp<JavaBBinder> mBinder中。而JavaBBinder继承自Native层的BBinder,还记得在IPC thread中接收binder的数据,并且通过BBinder回调的,然后再调用BnXX的onTransact执行Server端的相关命令

有了这些我们可以猜测IPowerManager.aidl编译出来的文件就是binder机制中Server端

现在既然知道了PowerManagerService是binder的server端,那他怎么在java层向binder注册呢,还有client端怎么在java层获取Service呢

首先,按着binder的机制,ServiceManager.addService(Context.POWER_SERVICE, power);

我们查看ServiceManager类

(frameworks/base/core/java/android/os/ServiceManager.java)

[java] view plaincopy
  1. public static void addService(String name, IBinder service, boolean allowIsolated) {
  2. try {
  3. getIServiceManager().addService(name, service, allowIsolated);
  4. } catch (RemoteException e) {
  5. Log.e(TAG, "error in addService", e);
  6. }
  7. }
  8. private static IServiceManager getIServiceManager() {
  9. if (sServiceManager != null) {
  10. return sServiceManager;
  11. }
  12. // Find the service manager
  13. sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());
  14. return sServiceManager;
  15. }

从代码可以看出addService是调用了ServiceManagerNative,而asInterface则是传入一个IBinder对象,并创建出ServiceManagerProxy,是不是跟Mediaplayer Server获取binder smgr有点类似?

[java] view plaincopy
  1. public void addService(String name, IBinder service, boolean allowIsolated)
  2. throws RemoteException {
  3. Parcel data = Parcel.obtain();
  4. Parcel reply = Parcel.obtain();
  5. data.writeInterfaceToken(IServiceManager.descriptor);
  6. data.writeString(name);
  7. data.writeStrongBinder(service);
  8. data.writeInt(allowIsolated ? 1 : 0);
  9. mRemote.transact(ADD_SERVICE_TRANSACTION, data, reply, 0);
  10. reply.recycle();
  11. data.recycle();
  12. }

我们在看看BinderInternal.getContextObject(),他是一个native函数,我们到native层看看是不是跟Mediaplayer Server一样通过new Bpbinder(0),获取到Binder smgr。

(framework\base\core\jni\android_util_Binder.cpp)

[cpp] view plaincopy
  1. static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
  2. {
  3. sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
  4. return javaObjectForIBinder(env, b);
  5. }
[cpp] view plaincopy
  1. jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
  2. {
  3. if (val == NULL) return NULL;
  4. if (val->checkSubclass(&gBinderOffsets)) {// BpBinder没重写,返回false
  5. // One of our own!
  6. jobject object = static_cast<JavaBBinder*>(val.get())->object();
  7. LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(), object);
  8. return object;
  9. }
  10. // For the rest of the function we will hold this lock, to serialize
  11. // looking/creation of Java proxies for native Binder proxies.
  12. AutoMutex _l(mProxyLock);
  13. // Someone else's...  do we know about it?
  14. // BpBinder没有带proxy过来
  15. jobject object = (jobject)val->findObject(&gBinderProxyOffsets);
  16. if (object != NULL) {
  17. jobject res = jniGetReferent(env, object);
  18. if (res != NULL) {
  19. ALOGV("objectForBinder %p: found existing %p!\n", val.get(), res);
  20. return res;
  21. }
  22. LOGDEATH("Proxy object %p of IBinder %p no longer in working set!!!", object, val.get());
  23. android_atomic_dec(&gNumProxyRefs);
  24. val->detachObject(&gBinderProxyOffsets);
  25. env->DeleteGlobalRef(object);
  26. }
  27. // 因为proxy,创建一个proxy
  28. // const char* const kBinderProxyPathName = "android/os/BinderProxy";
  29. object = env->NewObject(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mConstructor);
  30. if (object != NULL) {
  31. LOGDEATH("objectForBinder %p: created new proxy %p !\n", val.get(), object);
  32. // The proxy holds a reference to the native object.
  33. env->SetIntField(object, gBinderProxyOffsets.mObject, (int)val.get()); // 把BpBinder(0)赋值给BinderProxy 的mObject
  34. val->incStrong((void*)javaObjectForIBinder);
  35. // The native object needs to hold a weak reference back to the
  36. // proxy, so we can retrieve the same proxy if it is still active.
  37. jobject refObject = env->NewGlobalRef(
  38. env->GetObjectField(object, gBinderProxyOffsets.mSelf));
  39. val->attachObject(&gBinderProxyOffsets, refObject,
  40. jnienv_to_javavm(env), proxy_cleanup);
  41. // Also remember the death recipients registered on this proxy
  42. sp<DeathRecipientList> drl = new DeathRecipientList;
  43. drl->incStrong((void*)javaObjectForIBinder);
  44. env->SetIntField(object, gBinderProxyOffsets.mOrgue, reinterpret_cast<jint>(drl.get()));
  45. // Note that a new object reference has been created.
  46. android_atomic_inc(&gNumProxyRefs);
  47. incRefsCreated(env);
  48. }
  49. return object;
  50. }

可以看出返回了android.os.BinderProxy

也就是说ServiceManagerProxy的mRemote带的BinderProxy

frameworks/base/core/java/com/android/os/Binder.java)

而里面的Transact是调用native层的android_os_BinderProxy_transact

frameworks/base/core/jni/android/android.util.Binder.cpp)

[cpp] view plaincopy
  1. static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
  2. jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
  3. {
  4. if (dataObj == NULL) {
  5. jniThrowNullPointerException(env, NULL);
  6. return JNI_FALSE;
  7. }
  8. Parcel* data = parcelForJavaObject(env, dataObj);
  9. if (data == NULL) {
  10. return JNI_FALSE;
  11. }
  12. Parcel* reply = parcelForJavaObject(env, replyObj);
  13. if (reply == NULL && replyObj != NULL) {
  14. return JNI_FALSE;
  15. }
  16. IBinder* target = (IBinder*)
  17. env->GetIntField(obj, gBinderProxyOffsets.mObject); //此时的mObject为BpBinder(0);
  18. if (target == NULL) {
  19. jniThrowException(env, "java/lang/IllegalStateException", "Binder has been finalized!");
  20. return JNI_FALSE;
  21. }
  22. ALOGV("Java code calling transact on %p in Java object %p with code %d\n",
  23. target, obj, code);
  24. // Only log the binder call duration for things on the Java-level main thread.
  25. // But if we don't
  26. const bool time_binder_calls = should_time_binder_calls();
  27. int64_t start_millis;
  28. if (time_binder_calls) {
  29. start_millis = uptimeMillis();
  30. }
  31. //printf("Transact from Java code to %p sending: ", target); data->print();
  32. status_t err = target->transact(code, *data, reply, flags);
  33. //if (reply) printf("Transact from Java code to %p received: ", target); reply->print();
  34. if (time_binder_calls) {
  35. conditionally_log_binder_call(start_millis, target, code);
  36. }
  37. if (err == NO_ERROR) {
  38. return JNI_TRUE;
  39. } else if (err == UNKNOWN_TRANSACTION) {
  40. return JNI_FALSE;
  41. }
  42. signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/);
  43. return JNI_FALSE;
  44. }

看出status_t err = target->transact(code, *data, reply, flags);

是调用了BinderProxy里面mObject(Bpbinder(0))的transact来传输数据

可以看到跟Mediaplayer Server一样 获取了smgr binder,并通过他通讯给smgr binder

那我们可以归结出ServiceManagerProxy 为BpServicemanager,并带入了smgr binder,跟binder通讯

其次,我们在java层获取Service是通过

Context.getSystemService(Context.POWER_SERVICE);

getSystemService位于ContextImpl中

(frameworks/base/core/java/com/android/app/ContextImpl.java)

[java] view plaincopy
  1. @Override
  2. public Object getSystemService(String name) {
  3. ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name);
  4. return fetcher == null ? null : fetcher.getService(this);
  5. }
[java] view plaincopy
  1. Static{
  2. ....
  3. registerService(POWER_SERVICE, new ServiceFetcher() {
  4. public Object createService(ContextImpl ctx) {
  5. IBinder b = ServiceManager.getService(POWER_SERVICE);
  6. IPowerManager service = IPowerManager.Stub.asInterface(b);
  7. return new PowerManager(ctx.getOuterContext(),
  8. service, ctx.mMainThread.getHandler());
  9. }});
  10. ....
  11. };
[java] view plaincopy
  1. static class ServiceFetcher {
  2. int mContextCacheIndex = -1;
  3. /**
  4. * Main entrypoint; only override if you don't need caching.
  5. */
  6. public Object getService(ContextImpl ctx) {
  7. ArrayList<Object> cache = ctx.mServiceCache;
  8. Object service;
  9. synchronized (cache) {
  10. if (cache.size() == 0) {
  11. // Initialize the cache vector on first access.
  12. // At this point sNextPerContextServiceCacheIndex
  13. // is the number of potential services that are
  14. // cached per-Context.
  15. for (int i = 0; i < sNextPerContextServiceCacheIndex; i++) {
  16. cache.add(null);
  17. }
  18. } else {
  19. service = cache.get(mContextCacheIndex);
  20. if (service != null) {
  21. return service;
  22. }
  23. }
  24. service = createService(ctx);
  25. cache.set(mContextCacheIndex, service);
  26. return service;
  27. }
  28. }
  29. /**
  30. * Override this to create a new per-Context instance of the
  31. * service.  getService() will handle locking and caching.
  32. */
  33. public Object createService(ContextImpl ctx) {
  34. throw new RuntimeException("Not implemented");
  35. }
  36. }

从代码里面看出,要是从cache中获取不到service,那么

[java] view plaincopy
  1. Static{
  2. ....
  3. registerService(POWER_SERVICE, new ServiceFetcher() {
  4. public Object createService(ContextImpl ctx) {
  5. IBinder b = ServiceManager.getService(POWER_SERVICE);
  6. IPowerManager service = IPowerManager.Stub.asInterface(b);
  7. return new PowerManager(ctx.getOuterContext(),
  8. service, ctx.mMainThread.getHandler());
  9. }});
  10. ....
  11. };

通过ServiceManager获取到PowerService,并通过Stub转化成IPowerManager,并创建了PowerManager返回给客户端调用。

而getService函数就跟addService一样,先获取smgr,然后用ServiceManagerProxy 的getService获取到binder,然后通过stub的asInterface转化为IPowerManager(实际是让其带Service的Binder)

[java] view plaincopy
  1. public static android.os.IPowerManager asInterface(
  2. android.os.IBinder obj) {
  3. if ((obj == null)) {
  4. return null;
  5. }
  6. android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
  7. if (((iin != null) && (iin instanceof android.os.IPowerManager))) {
  8. return ((android.os.IPowerManager) iin);
  9. }
  10. return new android.os.IPowerManager.Stub.Proxy(obj);
  11. }
[java] view plaincopy
  1. Proxy(android.os.IBinder remote) {
  2. mRemote = remote;
  3. }

Java层Binder使用(ServiceManager)相关推荐

  1. 安卓高手之路之java层Binder

    很多人一提到Binder就说代理模式,人云亦云的多,能理解精髓的少. 本篇文章就从设计角度分析一下java层BInder的设计目标,以及设计思路,设计缺陷,从而驾驭它. 对于[邦德儿]的理解, 从通信 ...

  2. 理解Android Binder机制(3/3):Java层

    本文是Android Binder机制解析的第三篇,也是最后一篇文章.本文会讲解Binder Framework Java部分的逻辑. Binder机制分析的前面两篇文章,请移步这里: 理解Andro ...

  3. Binder源码分析之Java层(原)

    前面的几节中我们介绍了Native层Binder通讯的原理和用法,那么在Java层如何使用Binder通讯呢?其原理又与Native层的Binder有什么关系呢?         与Native层的S ...

  4. java层 native层_Java层的ServiceManager和Native层的ServiceManager的对应过程

    转自:https://blog.csdn.net/moonshine2016/article/details/54378358 参考:https://www.jianshu.com/p/9c02370 ...

  5. Android系统中的Binder通信机制分析(7)- Java 层的 Binder 机制

    声明 其实对于Android系统Binder通信的机制早就有分析的想法,记得2019年6.7月份Mr.Deng离职期间约定一起对其进行研究的,但因为我个人问题没能实施这个计划,留下些许遗憾- 文中参考 ...

  6. android binder - 客户端(c++层) 调用 服务端(java层),服务端回调客户端 例子

    学习了: android binder - 客户端(java层) 调用 服务端(c++层) 例子 http://blog.csdn.net/ganyue803/article/details/4131 ...

  7. Binder Java层实现(一):IBinder/IInterface/Binder/Stub

    要点 面向对象思想的引入将进程间通信转化为通过对某个Binder对象的引用调用该对象的方法,而其独特之处在于Binder对象是一个可以跨进程引用的对象,它的实体(本地对象)位于一个进程中,而它的引用( ...

  8. java 通信层_Android native进程间通信实例-binder篇之——HAL层访问JAVA层的服务

    有一天在群里聊天的时候,有人提出一个问题,怎样才能做到HAL层访问JAVA层的接口?刚好我不会,所以做了一点研究. 之前的文章末尾部分说过了service call 可以用来调试系统的binder服务 ...

  9. JAVA层HIDL服务的获取原理-Android10.0 HwBinder通信原理(九)

    摘要:本节主要来讲解Android10.0 JAVA层HIDL服务的获取原理 阅读本文大约需要花费19分钟. 文章首发微信公众号:IngresGe 专注于Android系统级源码分析,Android的 ...

最新文章

  1. python制作解压工具_使用python制作一个解压缩软件
  2. 第5章 用户身份与文件权限
  3. Vue:Elementui中的Tag与页面其它元素相互交互的两三事
  4. Mysql中(@i:=@i+1)的作用
  5. python基础知识资料-Python基础知识汇总
  6. 系统架构设计师证书含金量_计算机专科生不能错过的两个证书,含金量比较高,出社会有益...
  7. nltkdata路径设置linux,NLTK data路径设置
  8. 利用栈解决深度搜索问题
  9. 未将更新安装在此计算机上,Win7用户注意!7月前没安装这个更新包,将不能再使用更新功能!...
  10. 使用webpack前端重构感受
  11. 练习四十四:整数的排序
  12. Memcached笔记——(四)应对高并发攻击【转】
  13. 【活动】完整的Java学习路径《深入理解Java核心技术》(文末送书)
  14. 洛伦兹吸引子 matlab,混沌蝴蝶——洛伦兹吸引子
  15. 为什么说百度全面降低了中国互联网体验?
  16. fieldtrip学习——1.坐标系介绍(ctf坐标系和acpc坐标系简介)
  17. opencascade 0xXXXXXXXX处最可能的异常: 0xC0000005: 写入位置 0x00000014 时发生访问冲突
  18. 永定城 × 奇点云 | 数字新商贸的全国样板长什么样?
  19. ThinkPad E40取消FN功能键设置
  20. CentOS系统安装(7.8.2003)

热门文章

  1. EnterpriseDb公司的Postgres Enterprise Manager 安装图解
  2. Jsoup进阶之获取指定数据
  3. c语言实验数据类型体会,实验1-C语言开发环境使用和数据类型、运算符、表达式-实验总结与体会...
  4. matlab数据取整方法
  5. Linux学习笔记 --组管理和权限管理
  6. 工作两年总结(一句话)
  7. NLP---将改变您在未来的沟通方式的7种 nlp 技术 (第一部分(附原始论文))
  8. Javascript第五章location对象第五课
  9. python 类函数 成员函数_python内置函数类型,如何为新类型定义成员函数?
  10. pycharm添加python注释头_Pycharm自动添加头注释