// 送信ボタンを押すとMicroSmaSvrに接続されたプリンタに「こんにちは」と印字する例
package com.example.socksample;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new MyOnClickListener());
}
public class MyOnClickListener implements OnClickListener {
public void onClick(View view) {
Socket sock = null;
try {
//1B 40 初期化
//0D 印字復帰
//1B 52 08 国際文字の選択
//1B 74 01 文字コードテーブルの選択
//1C 43 01 JIS指定
//0A 印字改行
byte[] disp1 = {0x1B, 0x40, 0x0D, 0x1B, 0x52, 0x08, 0x1B, 0x74, 0x01, 0x1C, 0x43, 0x01};
byte[] disp2 = "こんにちは".getBytes("Shift_JIS");
byte[] disp3 = {0x0A};
byte[] disp = new byte[disp1.length + disp2.length + disp3.length];
System.arraycopy(disp1, 0, disp, 0, disp1.length);
System.arraycopy(disp2, 0, disp, disp1.length, disp2.length);
System.arraycopy(disp3, 0, disp, disp1.length + disp2.length, disp3.length);
sock = new Socket();
sock.connect(new InetSocketAddress(MicroSmaSvrのIPアドレス, MicroSmaSvrのポート番号));
OutputStream out = sock.getOutputStream();
if(view.getId() == R.id.button1) {
out.write(disp,0,disp.length);
}
} catch (Exception e) {
e.printStackTrace();
}
if(sock != null){
try {
sock.close();
sock = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
|