Android プログラミング 様々な通信

HTTP通信

 @Override
    public void onClick(View v) {
        String tag = (String)v.getTag();
        if(TAG_READ.equals(tag)){

//          スレッドの生成
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {

//           HTTP通信
                    try{
                        text = new String(http2data(URL));
                    }catch (Exception e){
                        text = null;
                    }

//           ハンドラの生成
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if(text != null){
                                editText.setText(text);
                            }else{
                                editText.setText("読み込み失敗しました");
                            }
                        }});

                }});
        thread.start();
        }
    }

    public static byte[] http2data(String path) throws Exception{
        byte[] w = new byte[1024];
        HttpURLConnection c = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try{

//         HTTP接続のオープン
            URL url = new URL(path);
            c = (HttpURLConnection)url.openConnection();
            c.setRequestMethod("GET");
            c.connect();
            in = c.getInputStream();

//         バイト配列の読み込み
            out = new ByteArrayOutputStream();
            while(true){
                int size = in.read(w);
                if (size <= 0)break;
                out.write(w,0,size);
            }
            out.close();

//         HTTP通信のクローズ
            in.close();
            c.disconnect();
            return out.toByteArray();
        }catch (Exception e){
            try{

            }catch (Exception e2){
                if(c!=null)c.disconnect();
                if(in!=null)in.close();
                if(out!=null)out.close();
            }
            throw e;
        }
    }

ソケット通信

@Override
    protected void onStart() {
        super.onStart();

//        スレッドの生成
        Thread thread = new Thread(){
            @Override
            public void run() {
                try{
                    connect(IP,8081);
                }catch (Exception e){
                }
            }
        };
        thread.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        disconnect();
    }

    private void addText(final String text){
//        受信テキストの追加
//        UI変えるからメインスレッドで処理させてる
        handler.post(new Runnable() {
            @Override
            public void run() {
                lblReceive.setText(text + BR + lblReceive.getText());
            }
        });
    }

    private void connect(String ip, int port){
        int size;
        String str;
        byte[] w = new byte[1024];

        try{
//            ソケット接続
            addText("接続中");
            socket = new Socket(ip,port);
            in = socket.getInputStream();
            out = socket.getOutputStream();
            addText("接続完了");

//            受信ループ
            while(socket != null && socket.isConnected()){
                size = in.read(w);
                if(size <= 0) continue;
                str = new String(w,0,size,"UTF-8");

//                受信データの追加
                addText(str);
            }
        }catch (Exception e){
            addText("通信失敗しました");
        }
    }

    private void disconnect(){
        try{
            socket.close();
            socket = null;
        }catch (Exception e){

        }
    }

    @Override
    public void onClick(View v) {
        Thread thread = new Thread(new Runnable() {
//            データ送信
            @Override
            public void run() {
                error = false;
                try{
                    if(socket != null && socket.isConnected()){
                        byte[] w = edtSend.getText().toString().getBytes("UTF8");
                        out.write(w);
                        out.flush();
                    }
                }catch (Exception e){
                    error = true;
                }

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if(!error){
                            edtSend.setText("");
                        }else{
                            addText("通信失敗しました");
                        }
                    }});
            }});
        thread.start();
    }

NFC通信

まず、Manifest.xmlに以下を追加

<uses-permission android:name="android.permission.NFC" />

~省略~

<intent-filter>
                <action android:name="android.nfc.action.TAG_DISCOVERED" />
                <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

そして、 Release08 - guava-libraries - Release notes for Guava Release 08 - Guava: Google Core Libraries for Java 1.6+ - Google Project Hosting からguava-r08.zip を落としてきて、 app/libsに追加してGradleに同期する。

    @Override
    protected void onResume() {
        super.onResume();
        try{
//            FelicaのmIDを取得
            byte[] mID = getIntent().getByteArrayExtra(NfcAdapter.EXTRA_ID);
//          バイトを16進に変換
            String hexStr = data2hex(mID);
            textView.setText("NFCEx>"+hexStr);
        }catch (Exception e){
            textView.setText("合わせてください");
        }
    }
    
//          バイトを16進に変換
    private String data2hex(byte[] data){
        StringBuilder sb = new StringBuilder();
        for (int i=0;i<data.length;i++){
            String str = Integer.toHexString(
                    UnsignedBytes.toInt(data[i]));
            if(str.length() == 1) sb.append("0");
            sb.append(str);
        }
        return sb.toString();
    }
}

参考文献