我创建了一个客户端 - 服务器应用程序,双方使用套接字连接和输入/输出流进行通信以发送/接收数据。这一切都很好但只有我只有一个使用连接的活动。由于我将在我的应用程序中不仅仅有一个活动,并且经过一些搜索后,我得出结论,我必须创建一个服务来处理套接字连接和从套接字流发送/接收。我之前从未使用过服务,我以为我会一步一步地开始。目前我刚刚创建了一个Service,它创建了我的Client类的实例(扩展了Thread)并启动了该线程,该线程建立了与服务器的连接。
我的客户班级
的 T_Client:
public class T_Client extends Thread {
private static final String TAG = "T_Client";
private static String serverIP = "192.168.2.3";
private static int port = 4444;
private InetAddress serverAddr = null;
private Socket sock = null;
private boolean running = false;
private ObjectInputStream in;
private ObjectOutputStream out;
private Object objIn;
public void send(MessageCustom _msg) {
if (out != null) {
try {
out.writeObject(_msg);
out.flush();
Log.i("Send Method", "Outgoing : " + _msg.toString());
} catch (IOException ex) {
Log.e("Send Method", ex.toString());
}
}
}
public void stopClient() {
Log.v(TAG,"stopClient method run");
running = false;
}
@Override
public void run() {
running = true;
try {
serverAddr = InetAddress.getByName(serverIP);
Log.i("TCP Client", "C: Connecting...");
sock = new Socket(serverAddr, port);
try {
out = new ObjectOutputStream(sock.getOutputStream());
in = new ObjectInputStream(sock.getInputStream());
Log.i(TAG, "C: Connected.");
while (running) {
objIn = in.readObject();
Log.i("Object Read Class", objIn.getClass().toString());
Log.i("Object Read", objIn.toString());
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + objIn + "'");
} catch (Exception e) {
Log.e(TAG, "S: Error", e);
} finally {
out.close();
in.close();
sock.close();
Log.i(TAG, "Closing socket: " + sock);
}
} catch (Exception e) {
Log.e(TAG, "C: Error", e);
}
}
}
我的服务类
的为MyService:
public class MyService extends Service {
private static final String TAG = "MyService";
private T_Client client;
@Override
public void onDestroy() {
Log.v(TAG, "onDestroy");
if (client != null) {
try {
client.stopClient();
} catch (Exception e) {
Log.e(TAG, "Error on close: " + e);
}
}
super.onDestroy();
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand");
client = new T_Client();
client.start();
Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
目前我在主要活动中所做的只是使用开始和停止按钮来启动/停止服务
public void start(View v){
Log.i(TAG,"Start pressed");
Intent intent=new Intent(getBaseContext(),MyService.class);
startService(intent);
}
public void stop(View v){
Log.i(TAG,"Stop pressed");
Intent intent=new Intent(getBaseContext(),MyService.class);
stopService(intent);
}
所以我的问题是:
非常感谢任何可以指导我解决问题的意见 先感谢您。
答案 0 :(得分:0)
如果有其他人遇到这个问题,那也有类似的问题,我设法通过玩这两个帖子中的代码来解决我的问题