ps:阅读本文 需要对android 多进程编程有一定了解。
1.Android中总共有几种方式进行IPC?
答:一共有两种,一种是binder 还有一种是socket。Binder 大家用的比较多。Socket很少有人用,这里给出一个利用Socket进行ipc通信的例子。
服务端代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
package com.example.administrator.socketipcdemo; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class ServerService extends Service { public static final int SERVER_PORT_NUMBER = 5678; private boolean mServiceDestroyed = false; @Override public void onCreate() { new Thread(new ServerRunnable()).start(); super.onCreate(); } @Override public void onDestroy() { mServiceDestroyed = true; super.onDestroy(); } public ServerService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } //这个线程 用于监听端口号 class ServerRunnable implements Runnable { @Override public void run() { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(SERVER_PORT_NUMBER); } catch (IOException e) { e.printStackTrace(); } while (!mServiceDestroyed) { try { final Socket client = serverSocket.accept(); new Thread() { @Override public void run() { try { responseClientRequest(client); } catch (IOException e) { e.printStackTrace(); } } }.start(); } catch (IOException e) yon-striped-line" id="crayon-5812b9915fdca551938448-68"> } catch (IOException e) n Syntax Highlighter v2.7.1.1 -->
|