我刚收到一个简短的问题。我正在尝试制作一个可以通过发送 TCP 包与服务器通信的应用程序,然后服务器将 TCP 包发送回或发送到其他设备。但是,当设备上接收到 TCP 包时,我如何提供服务来发出通知?
我试过这个;
extends Service {
Thread henk;
private static final String TAG = "Service";
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
henk = new Thread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
Boolean end = false;
ServerSocket ss = new ServerSocket(1337);
while(!end){
//Server is waiting for client here, if needed
Socket s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String st = input.readLine();
Log.d("Tcp Example", "From client: "+st);
s.close();
}
ss.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
henk.run();
}
但这只会使我的应用程序崩溃。请帮忙?
堆栈跟踪:
E/ActivityManager( 240): ANR in tictactoe.elqauto
E/ActivityManager( 240): Reason: Executing service tictactoe.elqauto/.servicere
cieve
E/ActivityManager( 240): Load: 7.09 / 7.29 / 7.5
E/ActivityManager( 240): CPU usage from 9411ms to 3791ms ago:
E/ActivityManager( 240): 1.2% 3857/de.devmil.minimaltext: 1.1% user + 0.1% ke
rnel / faults: 191 minor
E/ActivityManager( 240): 2.5% 240/system_server: 1.9% user + 0.5% kernel / fa
ults: 20 minor
E/ActivityManager( 240): 0.1% 4797/tiwlan_wq: 0% user + 0.1% kernel
E/ActivityManager( 240): 0% 16322/org.adwfreak.launcher: 0% user + 0% kernel
/ faults: 226 minor 1 major
E/ActivityManager( 240): 0% 19108/com.aricent.mtp: 0% user + 0% kernel / faul
ts: 16 minor
E/ActivityManager( 240): 0% 30600/com.google.process.gapps: 0% user + 0% kern
el / faults: 20 minor 5 major
E/ActivityManager( 240): 11% TOTAL: 8% user + 3% kernel + 0.1% iowait
E/ActivityManager( 240): CPU usage from 368ms to 884ms later:
E/ActivityManager( 240): 5.6% 240/system_server: 1.8% user + 3.7% kernel / fa
ults: 15 minor
E/ActivityManager( 240): 5.6% 266/ActivityManager: 1.8% user + 3.7% kernel
E/ActivityManager( 240): 44% TOTAL: 1.9% user + 1.9% kernel + 40% iowait
概括:
所以我要做的是向服务器发送一个带有名称的 TCP 包,服务器将从数据库中获取属于该名称的 IP,并向它发送一个带有一些信息的 TCP 包。由于我没有找到解决方案,我尝试了套接字,但现在我被困在接收部分。