androidとnodeの連携

androidでDB使いたいなー、他の機と通信したいなーなんてことあると思います。
そこで、android と node の連携のサンプルを作ってみたいと思います。

まずはnodeで簡単な文字列を送信して、androidで表示させてみようと思います。


node側

今回はexpressを使いたいと思います。予めインストールしておいてください。
以下のコードで起動しておきます。

var app = require("express")();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.get("/", function(req, res){
    res.send("Hello world");
});

app.listen(3000);


一回テストしてみます。


[f:id:koooya:20141015091009p:plain



android

レイアウトはすごく簡単に
f:id:koooya:20141015091544p:plain
ボタンを押したら、TextViewの文字が変わるようにします。

ではソースの方を

public class MyActivity extends Activity {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        textView = (TextView)findViewById(R.id.textView);
        Button btn = (Button)findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                AsyncGetStringTask task = new AsyncGetStringTask(textView);
                task.execute();
            }
        });
    }

    .......
    .......
    .......

    class AsyncGetStringTask extends AsyncTask<String , String, String> {
        private TextView textView;

        AsyncGetStringTask(TextView textView){
            this.textView = textView;
        }
        @Override
        protected String doInBackground(String... strings) {

            try{
                HttpGet httpGet = new HttpGet("/*nodeの場所*/");

                DefaultHttpClient client = new DefaultHttpClient();

                HttpResponse httpResponse = client.execute(httpGet);

                //int statusCode = httpResponse.getStatusLine().getStatusCode();

                HttpEntity entity = httpResponse.getEntity();

                String response = EntityUtils.toString(entity);

                entity.consumeContent();
                client.getConnectionManager().shutdown();

                return  response;

            }catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        };
        @Override
        protected void onPostExecute(String response){
            textView.setText(response);
        }
    }
}


ポイントは、UIスレッドでHTTP通信しようとすると怒られるので、マルチタスクで通信してるところです。
doInBackgroundでバックグラウンドで処理してる時にUIをいじろうとすると、これまたUIスレッドじゃないのにUIいじろうとするなって怒られるので、
いじるなら基本的にはonPostExecute内で。
どうしても使いたいならhttp://developer.android.com/reference/android/os/Handler.html

実行ー
f:id:koooya:20141015094253p:plain
f:id:koooya:20141015094300p:plain

とれてますね
文字を変えてみましょう。

app.get("/", function(req, res){
    res.send("AAAAAAAAAA");
});

f:id:koooya:20141015094650p:plain


文字じゃなくてjson使うときは

app.get("/", function(req, res){
    res.json({name: "hoge", age: "98"});
});
.....
.....
class AsyncGetStringTask extends AsyncTask<String , String, String> {
        ......
        ......
        @Override
        protected void onPostExecute(String response){
            JSONObject jsonObject = new JSONObject(response);
            String name = jsonObject.getString("name");
            String age = jsonObject.getString("age");
        }

みたいにやればOK