Страницы

Поиск по вопросам

понедельник, 17 июня 2019 г.

Почему не получается отправить координаты GPS на сервер?

Добрый день, пытаюсь отослать полученные GPS-координаты на сервер, если их выводить в консоль то всё в порядке но когда пробую отправить их на сервер приложение падает.
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
protected void onResume() { super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER/*ТИП ПРОВАЙДЕРА*/,// НА ВХОД ЕМУ ПОДАЁМ 1000 * 10/*МИНИМАЛЬНОЕ ВРЕМЯ ЗАПРОСА КООРДИНАТ*/, 10/*РАСТОЯНИЕ ОТОЙДЯ НА КОТОРОЕ ОБНОВЛЯЮТСЯ КООРДИНАТЫ*/, locationListener); }
@Override protected void onPause() {//ОТКЛЮЧАЕМ СЛУШАТЕЛЯ МЕТОДА removeUpdates super.onPause(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } locationManager.removeUpdates(locationListener); }
private LocationListener locationListener = new LocationListener() {
@Override public void onLocationChanged(Location location) { showLocation(location); coordinatesGPS (); }
@Override public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override public void onProviderDisabled(String provider) { checkDisabled1(); checkDisabled2(); }
@Override public void onProviderEnabled(String provider) {
}
};
private void showLocation(Location location) { if (location == null) return;
dataGPS1 = formatLocation1(location); dataGPS2 = formatLocation2(location); }
public String formatLocation1(Location location) { if (location == null) return ""; return String.format( "%1$.4f", location.getLatitude(), location.getLongitude());
}
public String formatLocation2(Location location) { if (location == null) return ""; return String.format( "%2$.4f", location.getLatitude(), location.getLongitude());
}
private void checkDisabled1() { dataGPS1 = "00,0000";
}
private void checkDisabled2() { dataGPS2 = "00,0000";
}
public void coordinatesGPS () {
String datGPS1 = dataGPS1;
System.out.println("Координаты =" + datGPS1); try { //---------------------------------------------- client = new Socket("192.168.1.138"/*192.168.1.138"*/, 58000); //----------------------------------------------
DataOutputStream outData = new DataOutputStream(client.getOutputStream());
outData.writeUTF(datGPS1);
} catch (IOException e) { e.printStackTrace(); } }
Ошибка.
08-29 11:33:53.556 23612-23612/gpstracker I/System.out: Координаты =89,1706 08-29 11:33:53.556 23612-23612/gpstracker D/AndroidRuntime: Shutting down VM 08-29 11:33:53.556 23612-23612/gpstracker W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x418e4c08) 08-29 11:33:53.566 23612-23612/gpstracker E/AndroidRuntime: FATAL EXCEPTION: main Process: gpstracker, PID: 23612 at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1166) at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) at libcore.io.IoBridge.connectErrno(IoBridge.java:127) at libcore.io.IoBridge.connect(IoBridge.java:112) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.Socket.startupSocket(Socket.java:567) at java.net.Socket.tryAllAddresses(Socket.java:128) at java.net.Socket.(Socket.java:178) at java.net.Socket.(Socket.java:150) at gpstracker.MainActivity.coordinatesGPS(MainActivity.java:137) at gpstracker.MainActivity$1.onLocationChanged(MainActivity.java:73) at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:279) at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:208) at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:224) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:146) at android.app.ActivityThread.main(ActivityThread.java:5603) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) at dalvik.system.NativeStart.main(Native Method)


Ответ

Задачи связанные с доступом в интернет, рекомендуется делать в фоне. AsyncTask или Service, например.
Так же попробуйте:
if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); }

Комментариев нет:

Отправить комментарий