进程间通信——AIDL&IPC

作者:追风剑情 发布于:2016-8-13 16:39 分类:Android

Android接口定义语言(AIDL)

进程间通信(IPC)

示例一:Activity与Service之间利用IPC机制通信

一、创建IDateTimeService.aidl

  1. package com.test.androidtest;
  2.  
  3. interface IDateTimeService {
  4. String getCurrentDateTime(in String format);
  5. }

 

二、创建DateTimeService.java

  1. package com.test.androidtest;
  2.  
  3. import android.app.Service;
  4. import android.content.Intent;
  5. import android.os.IBinder;
  6. import android.os.RemoteException;
  7.  
  8. public class DateTimeService extends Service{
  9.  
  10. IBinder dateTimeService = new IDateTimeService.Stub() {
  11. @Override
  12. public String getCurrentDateTime(String format) throws RemoteException {
  13. return "1900-05-10";
  14. }
  15. };
  16. @Override
  17. public IBinder onBind(Intent intent) {
  18. return dateTimeService;
  19. }
  20. }

 

三、创建MainActivity.java

  1. package com.test.androidtest;
  2.  
  3. import android.app.Activity;
  4. import android.os.IBinder;
  5. import android.os.Bundle;
  6. import android.os.RemoteException;
  7. import android.content.Context;
  8. import android.content.Intent;
  9. import android.content.ServiceConnection;
  10.  
  11. public class MainActivity extends Activity
  12. {
  13. Intent intent;
  14. @Override
  15. protected void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.fragment_main);
  18. //启动时间服务
  19. intent = new Intent(MainActivity.this, DateTimeService.class);
  20. bindService(intent, connection, Context.BIND_AUTO_CREATE);
  21. }
  22. private ServiceConnection connection = new ServiceConnection(){
  23. @Override
  24. public void onServiceConnected(ComponentName name, IBinder service) {
  25. Log.d("test", "连接DateTimeService成功!");
  26. IDateTimeService dateTimeService = IDateTimeService.Stub.asInterface(service);
  27. Log.d("test", "service="+dateTimeService);
  28. try {
  29. Log.d("test", "时间="+dateTimeService.getCurrentDateTime(""));
  30. } catch (RemoteException e) {
  31. e.printStackTrace();
  32. }
  33. startService(intent);
  34. }
  35.  
  36. @Override
  37. public void onServiceDisconnected(ComponentName name) {
  38. Log.d("test", "连接DateTimeService失败!");
  39. }
  40. };
  41. }

 

运行测试

1111111.png

 

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号