import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class Socketservice extends Service {
public String SERVERIP = "IP주소";
public int SERVERPORT = 3333;
DataOutputStream out;
DataInputStream in;
int data;
Socket socket;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
System.out.println("I am in Ibinder onBind method");
return myBinder;
}
private final IBinder myBinder = new LocalBinder();
// TCPClient mTcpClient = new TCPClient();
public class LocalBinder extends Binder {
public Socketservice getService() {
return Socketservice.this;
}
}
@Override
public void onCreate() {
super.onCreate();
System.out.println("I am in on create");
}
public void IsBoundable() {
Toast.makeText(this, "I bind like butter", Toast.LENGTH_LONG).show();
}
public void sendMessage(int message) throws IOException {
if (out != null) {
out.writeInt(message);
out.flush();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
System.out.println("I am in on start");
Toast.makeText(this, "Service created ...", Toast.LENGTH_LONG).show();
Runnable connect = new connectSocket();
new Thread(connect).start();
return START_STICKY;
}
class connectSocket implements Runnable {
@Override
public void run() {
try {
// here you must put your computer's IP address.
Log.e("TCP Client", "C: Connecting...");
// create a socket to make the connection with the server
socket = new Socket(SERVERIP, SERVERPORT);
try {
// send the message to the server
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
while (true) {
data = in.read();
}
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
try {
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
socket = null;
}
}
우선 소스는 이렇구 소켓 통신으로 액티비티간에 유지시키려고 서비스로 소켓을 연결까지
됩니다. 그런데 여기서 데이터를 어떻게 보내야 하나요?