Android LocalSocket使用

一、概述

LocalSocket可以在Android上实现跨进程的通信;区分服务端和客户端,服务端需要监听客户端发送过来的消息。

二、服务端实现

xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tvMsg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="300dp"
        android:text="收到消息"
        android:textColor="#000000" />

    <TextView
        android:background="#888888"
        android:id="@+id/tvToSend"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:text="去发送信息"
        android:textColor="#000000" />

</LinearLayout>

java代码

public class LocalSocketServerActivity extends Activity {

    private TextView tvMsg;

    private LocalServerSocket mServerSocket = null;
    private LocalSocket mSocket = null;

    private InputStream mInputStream = null;
    private static final String SOCKET_NAME = "demos.android.stormdzh.com.androiddemos.localsocket";
    private static final String TAG = LocalSocketServerActivity.class.getSimpleName();


    private final Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            String dispMesg = (String) msg.obj;
            tvMsg.setText(dispMesg);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_local_socket_server);

        tvMsg = findViewById(R.id.tvMsg);

        createServerSocket();// 创建LocalServerSocket

        //必须要在子线程里接收消息
        new Thread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void run() {
                acceptMsg();
            }
        }).start();

        findViewById(R.id.tvToSend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LocalSocketServerActivity.this,LocalSocketClientActivity.class));
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void acceptMsg() {
        try {
            mSocket = mServerSocket.accept();//accept是个阻塞方法,这就是必须要在子线程接收消息的原因。
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        while (true) {
            try {
                byte[] buffer = new byte[1024];
                mInputStream = mSocket.getInputStream();
                int count = mInputStream.read(buffer);
                String key = new String(Arrays.copyOfRange(buffer, 0, count));
                Log.d(TAG, "ServerActivity mSocketOutStream==" + key);
                if ("stop".equals(key)) {
                    closeSocketResource();
                    break;
                }
                Message msg = mHandler.obtainMessage();
                msg.obj = key;
                msg.sendToTarget();
            } catch (IOException e) {
                Log.d(TAG, "exception==" + e.fillInStackTrace().getMessage());
                e.printStackTrace();
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void closeSocketResource() {
        closeSlient(mInputStream);
        closeSlient(mSocket);
        try {
            if (mServerSocket != null) {
                mServerSocket.close();
                mServerSocket = null;
            }
        } catch (IOException ex) {
            Log.e(TAG, "Failed closing ServerSocket" + ex.fillInStackTrace());
        }
    }

    private void closeSlient(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
                closeable = null;
            }
        } catch (IOException ex) {
            Log.e(TAG, "Failed closing : " + closeable);
        }
    }

    private void createServerSocket() {

        if (mServerSocket == null) {
            try {
                /**注意这里new出LocalServerSocket的同时,系统层已经同步做了bind和listen。
                 * 我们看看new的过程:
                 * public LocalServerSocket(String name) throws IOException {
                 *       impl = new LocalSocketImpl();
                 *       impl.create(LocalSocket.SOCKET_STREAM);
                 *       localAddress = new LocalSocketAddress(name);
                 *       impl.bind(localAddress);
                 *       impl.listen(LISTEN_BACKLOG);
                 * }
                 */
                mServerSocket = new LocalServerSocket(SOCKET_NAME);
            } catch (IOException ex) {
            }
        }
    }
}

三、客户端实现

xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/input_msg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp" />

    <TextView
        android:id="@+id/replay_btn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="10dp"
        android:background="#765432"
        android:gravity="center"
        android:text="回复"
        android:textColor="#000000" />


    <TextView
        android:id="@+id/stop_btn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="10dp"
        android:background="#888888"
        android:gravity="center"
        android:text="关闭"
        android:textColor="#000000" />

</LinearLayout>

java代码

public class LocalSocketClientActivity extends Activity implements View.OnClickListener {

    private EditText mEditText;

    private LocalSocket mSocket;
    private OutputStream mOut;
    private static final String SOCKET_NAME = "demos.android.stormdzh.com.androiddemos.localsocket";
    private static final String TAG = LocalSocketServerActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_socket_client);
        connect();
        mEditText = (EditText) findViewById(R.id.input_msg);
        findViewById(R.id.replay_btn).setOnClickListener(this);
        findViewById(R.id.stop_btn).setOnClickListener(this);
    }

    private boolean connect() {
        if (mSocket != null) {
            return true;
        }
        try {
            mSocket = new LocalSocket();//创建LocalSocket,模拟客户端
            LocalSocketAddress address = new LocalSocketAddress(SOCKET_NAME,
                    LocalSocketAddress.Namespace.ABSTRACT);
            mSocket.connect(address);//连接TestLocalSocketServer
        } catch (IOException ex) {
            return false;
        }
        return true;
    }

    private boolean writeCommand(String cmdString) {
        final byte[] cmd = cmdString.getBytes();
        final int len = cmd.length;
        try {
            mOut = mSocket.getOutputStream();
            mOut.write(cmd, 0, len);
            Log.i(TAG, "ClientActivity write " + new String(cmd));
        } catch (IOException ex) {
            Log.e(TAG, "ClientActivity write error:" + ex.fillInStackTrace());
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.replay_btn:
                writeCommand(mEditText.getText().toString());
                break;
            case R.id.stop_btn:
                writeCommand("stop");
                break;
            default:
                break;
        }

    }
}

四、验证

首先进入到服务端页面,之后点击“去发送信息”按钮到达客户端页面,在客户端输入文本,发送即可。如果希望测试跨进程可以把客户端的Activity配置成一个单独进程:

 <activity android:name=".localsocket.LocalSocketClientActivity"
            android:process="com.localsocket.process"
            />

推荐阅读更多精彩内容