最近一个项目中需跨进程通信,对Windows来说So easy~,结果在Android上让我快崩溃了,尝试了3个方案,优缺点如下:
通过文件通信,不评价了。通过AM命令通信,适合频率低、数据少,单工的通知,数据量、频率一大就呵呵了。通过Socket通信,适合频率高,数据大,双工的交互,效果棒棒达~ 顺便列一下Windows平台进程间的通信,如数家珍啊,给Android参考一下: ClipboardCOMData CopyDDEFile MappingMailslotsPipesRPCWindows SocketsMemory Share 贴一点点示例代码: 服务端: char buffer[BUFSIZE] = {0}; m_fdListen = android_get_control_socket("hipsd"); if (-1 == m_fdListen) { goto exit; } if (listen(m_fdListen, 1) < 0) { goto exit; } fcntl(m_fdListen, F_SETFD, FD_CLOEXEC); do { m_fdControl = accept(m_fdListen, NULL, 0); if (m_fdControl < 0) { continue; } fcntl(m_fdControl, F_SETFD, FD_CLOEXEC); do { if (m_queue.size() > 0) { char* p = m_queue.front(); memset(buffer, 0, BUFSIZE); strcpy(buffer, p); buffer[BUFSIZE - 1] = '\0'; delete[] p; p = NULL; if (___DBG) { ALOGD("SiteChecker::InitSocket->send: %lu,%s", m_queue.size(), buffer); } send(m_fdControl, buffer, strlen(buffer), 0); m_mutex2 = 1; m_queue.pop(); m_mutex2 = 0; } else { sleep(2); } } while(true); close(m_fdControl); sleep(2); } while (true); close(m_fdListen); 客户端: LocalSocketAddress lsa = new LocalSocketAddress("hipsd", LocalSocketAddress.Namespace.RESERVED); int count = 0; int len = 128; while(count++ < 99) { LocalSocket ls = new LocalSocket(); try { ls.connect(lsa); byte[] buffer = new byte[len]; while(true) { InputStream is = ls.getInputStream(); int bytes = is.read(buffer, 0, len); if (bytes < 0) { break; } else if (bytes >= len) { bytes = len - 1; } String srcData = new String(buffer, 0, bytes, "utf-8"); // onGetUrl(mContext, srcData); } } catch (Exception e) { Slog.d("SiteChecker", "Exception:" + e.toString()); } finally { try{ ls.close(); ls = null; } catch (IOException e) {} } try { Thread.sleep(5000); Slog.d("SiteChecker", "connect..." + count); } catch( InterruptedException e) {} }