마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

Socket 통신으로 인한 서비스에서 데이터 보내기

0 추천
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;
 }

}

우선 소스는 이렇구 소켓 통신으로 액티비티간에 유지시키려고 서비스로 소켓을 연결까지

됩니다. 그런데 여기서 데이터를 어떻게 보내야 하나요?
열심히하는 (160 포인트) 님이 2014년 11월 7일 질문

답변 달기

· 글에 소스 코드 보기 좋게 넣는 법
· 질문에 대해 추가적인 질문이나 의견이 있으면 답변이 아니라 댓글로 달아주시기 바랍니다.
표시할 이름 (옵션):
개인정보: 당신의 이메일은 이 알림을 보내는데만 사용됩니다.
스팸 차단 검사:
스팸 검사를 다시 받지 않으려면 로그인하거나 혹은 가입 하세요.
...