[关闭]
@mSolo 2015-04-23T17:51:08.000000Z 字数 3233 阅读 1616

Android 知识碎片笔记(三)

Android


11. Binder

12. Messenger

  1. public void onServiceConnected(ComponentName name, IBinder service) {
  2. mMessenger = new Messenger(service);     
  3. // ......
  4. }
  1. public class WorkerThreadService extends Service {
  2. WorkerThread mWorkerThread;
  3. Messenger mWorkerMessenger;
  4. @Override
  5. public void onCreate() {
  6. super.onCreate();
  7. mWorkerThread.start();
  8. }
  9. /**
  10. * Worker thread has prepared a looper and handler.
  11. **/
  12. private void onWorkerPrepared() {
  13. mWorkerMessenger = new Messenger(mWorkerThread.mWorkerHandler);
  14. }
  15. public IBinder onBind(Intent intent) {
  16. return mWorkerMessenger.getBinder();
  17. }
  18. @Override
  19. public void onDestroy() {
  20. super.onDestroy();
  21. mWorkerThread.quit();
  22. }
  23. private class WorkerThread extends Thread {
  24. Handler mWorkerHandler;
  25. @Override
  26. public void run() {
  27. Looper.prepare();
  28. mWorkerHandler = new Handler() {
  29. @Override
  30. public void handleMessage(Message msg) {
  31. // Implement message processing
  32. }
  33. };
  34. onWorkerPrepared();
  35. Looper.loop();
  36. }
  37. public void quit() {
  38. mWorkerHandler.getLooper().quit();
  39. }
  40. }
  41. }
  1. public void onSendClick(View v) {
  2. if (mBound) {
  3. try {
  4. Message msg = Message.obtain(null, 1, 0, 0);
  5. msg.replyTo = new Messenger(new Handler() {
  6. @Override
  7. public void handleMessage(Message msg) {
  8. Log.d(TAG, "Message sent back - msg.what = " + msg.what);
  9. }
  10. });
  11. mRemoteService.send(msg);
  12. } catch (RemoteException e) {
  13. Log.e(TAG, e.getMessage());
  14. }
  15. }
  16. }
  17. // remote service
  18. public void run() {
  19. Looper.prepare();
  20. mWorkerHandler = new Handler() {
  21. @Override
  22. public void handleMessage(Message msg) {
  23. switch (msg.what) {
  24. case 1:
  25. try {
  26. msg.replyTo.send(Message.obtain(null, msg.what, 0, 0));
  27. } catch (RemoteException e) {
  28. Log.e(TAG, e.getMessage());
  29. }
  30. break;
  31. }
  32. }
  33. };
  34. onWorkerPrepared();
  35. Looper.loop();
  36. }
  37. }

13. 理解 VSYNC

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注