我想将位置数据从一台服务器平板电脑发送到1(或更多)客户端平板电脑。
服务器
public class MainActivity extends Activity {
private LocationManager locationManager;
private LocationListener myLocListener;
private String message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLocListener = new MyLocationListener();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, myLocListener);
} catch (SecurityException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
NetworkThread x = new NetworkThread();
x.start();
}
private class NetworkThread extends Thread{
@Override
public void run() {
try{
ServerSocket ss = new ServerSocket(8080);
Socket cl1 = ss.accept();
PrintWriter pw1 = new PrintWriter(cl1.getOutputStream());
while(true){
if(message!=null){
pw1.println(message);
pw1.flush();
}
}
} catch (Exception e){
e.printStackTrace();
}
}
}
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(final Location location) {
message = "lat:" + String.valueOf(location.getLatitude()) + " lon:" + String.valueOf(location.getLongitude() +
" time:" + String.valueOf(location.getTime()));
}
@Override
public void onProviderDisabled(String arg0) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
客户端
public class MainActivity extends Activity {
private TextView Messages;
private Activity MainAct;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainAct = this;
Messages = (TextView) findViewById(R.id.msg);
NetworkThread x = new NetworkThread();
x.start();
}
public class NetworkThread extends Thread{
public void run(){
try{
Socket s = new Socket(getIpAddress(),8080);
final Scanner sc = new Scanner(s.getInputStream());
while(true){
try{
MainAct.runOnUiThread(new Runnable() {
@Override
public void run() {
Messages.append(sc.nextLine());
}
});
} catch (Exception ex){
ex.printStackTrace();
}
}
} catch (Exception e){
e.printStackTrace();
}
}
}
}
不幸的是,它不起作用,服务器从GPS获取坐标,但客户端没有收到它们。