Android LocalSocket使用

8234 ワード

一、概説
LocalSocketはAndroid上でプロセス間の通信を実現することができる.サービス側とクライアントを区別し、サービス側はクライアントから送信されたメッセージを傍受する必要がある.
二、サービス側実現
xmlファイル



    

    


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ファイル



    

    


    


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を別のプロセスに構成できます.