使用spring的post服务从android在数据库中插入当前位置

8nuwlpux  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(347)

我在javaspring中有一个post服务,我想用它从android客户端获取当前位置并插入mysql数据库。我的邮政服务经过了 swagger 的测试,效果很好。在android中,我有下一个代码:

  1. public class SendActivity extends AppCompatActivity implements View.OnClickListener {
  2. private Executor executor = Executors.newFixedThreadPool(1);
  3. private LocationManager locationManager;
  4. private String provider;
  5. private static final int REQUEST_LOCATION = 1;
  6. TextView textView;
  7. private volatile Handler msgHandler;
  8. private static final String STATIC_LOCATION =
  9. "{" +
  10. "\"terminalId\":\"%s\"," +
  11. "\"latitude\":\"%s\"," +
  12. "\"longitude\":\"%s\"" +
  13. "}";
  14. @Override
  15. protected void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.activity_send);
  18. textView = (TextView) findViewById(R.id.text_location);
  19. Button sendButton = findViewById(R.id.button_location);
  20. sendButton.setOnClickListener(this);
  21. msgHandler = new MsgHandler(this);
  22. }
  23. public void onClick(View v) {
  24. executor.execute(new Runnable() {
  25. public void run() {
  26. Message msg = msgHandler.obtainMessage();
  27. // use MAC addr or IMEI as terminal id
  28. // read true position
  29. // replace static coordinates with the ones from the true position
  30. msg.arg1 = sendCoordinates("123456", "23.25", "45.02") ? 1 : 0;
  31. msgHandler.sendMessage(msg);
  32. }
  33. });
  34. }
  35. private boolean sendCoordinates(String terminalId, String lattitude, String longitude) {
  36. HttpURLConnection con = null;
  37. try {
  38. if (ActivityCompat.checkSelfPermission(SendActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
  39. != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
  40. (SendActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  41. ActivityCompat.requestPermissions(SendActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
  42. } else {
  43. Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
  44. Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
  45. Location location2 = locationManager.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER);
  46. if (location != null) {
  47. double latti = location.getLatitude();
  48. double longi = location.getLongitude();
  49. lattitude = String.valueOf(latti);
  50. longitude = String.valueOf(longi);
  51. textView.setText("Your current location is"+ "\n" + "Lattitude = " + lattitude
  52. + "\n" + "Longitude = " + longitude);
  53. } else if (location1 != null) {
  54. double latti = location1.getLatitude();
  55. double longi = location1.getLongitude();
  56. lattitude = String.valueOf(latti);
  57. longitude = String.valueOf(longi);
  58. textView.setText("Your current location is"+ "\n" + "Lattitude = " + lattitude
  59. + "\n" + "Longitude = " + longitude);
  60. } else if (location2 != null) {
  61. double latti = location2.getLatitude();
  62. double longi = location2.getLongitude();
  63. lattitude = String.valueOf(latti);
  64. longitude = String.valueOf(longi);
  65. textView.setText("Your current location is"+ "\n" + "Lattitude = " + lattitude
  66. + "\n" + "Longitude = " + longitude);
  67. }else{
  68. Toast.makeText(this,"Unble to Trace your location",Toast.LENGTH_SHORT).show();
  69. }
  70. }
  71. URL obj = new URL("http://192.168.0.102:8085/position/send");
  72. con = (HttpURLConnection) obj.openConnection();
  73. con.setRequestMethod("POST");
  74. con.setRequestProperty("User-Agent", "Mozilla/5.0");
  75. con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
  76. con.setDoOutput(true);
  77. OutputStream os = con.getOutputStream();
  78. os.write(String.format(STATIC_LOCATION, terminalId, lattitude, longitude).getBytes());
  79. os.flush();
  80. os.close();
  81. int responseCode = con.getResponseCode();
  82. if (responseCode == HttpURLConnection.HTTP_OK) { //success
  83. BufferedReader in = new BufferedReader(new InputStreamReader(
  84. con.getInputStream()));
  85. String inputLine;
  86. StringBuilder response = new StringBuilder();
  87. while ((inputLine = in.readLine()) != null) {
  88. response.append(inputLine);
  89. }
  90. in.close();
  91. return true;
  92. } else {
  93. return false;
  94. }
  95. } catch (Exception e) {
  96. // e.printStackTrace();
  97. return false;
  98. } finally {
  99. if (con != null) {
  100. con.disconnect();
  101. }
  102. }
  103. }
  104. private static class MsgHandler extends Handler {
  105. private final WeakReference<Activity> sendActivity;
  106. public MsgHandler(Activity activity) {
  107. sendActivity = new WeakReference<>(activity);
  108. }
  109. @Override
  110. public void handleMessage(Message msg) {
  111. if (msg.arg1 == 1) {
  112. Toast.makeText(sendActivity.get().getApplicationContext(),
  113. "Success!", Toast.LENGTH_LONG).show();
  114. } else {
  115. Toast.makeText(sendActivity.get().getApplicationContext(),
  116. "Error!", Toast.LENGTH_LONG).show();
  117. }
  118. }
  119. }
  120. }

我知道我的变量“string terminalid,string latitude”被覆盖,但是这个方法是一个测试方法。每次运行时,我都会收到以下错误消息:

  1. Toast.makeText(sendActivity.get().getApplicationContext(),
  2. "Error!", Toast.LENGTH_LONG).show();

我需要一点帮助这个代码,因为我不知道为什么应用程序不能工作。

hfyxw5xn

hfyxw5xn1#

昨晚我花了很多时间来解决这个问题。我解决了这个问题,问题是当我尝试从线程获取gps的位置时:

  1. private Executor executor = newFixedThreadPool(1);

更确切地说,在methon:

  1. private boolean sendCoordinates(String terminalId, String lattitude, String longitude)

在线程中调用:

  1. executor.execute(new Runnable() {
  2. public void run() {
  3. Message msg = msgHandler.obtainMessage();
  4. msg.arg1 = sendCoordinates("123456", "23.25", "45.02") ? 1 : 0;
  5. msgHandler.sendMessage(msg);
  6. }
  7. });

为了解决这个问题,我提出了另一种方法来获取位置并将这个日期保存在一个局部变量中,在我的例子中有两个文本视图:

  1. private void getLocation() {
  2. if (ActivityCompat.checkSelfPermission(SendActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
  3. != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
  4. (SendActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  5. ActivityCompat.requestPermissions(SendActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
  6. } else {
  7. Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
  8. Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
  9. Location location2 = locationManager.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER);
  10. if (location != null) {
  11. double latti = location.getLatitude();
  12. double longi = location.getLongitude();
  13. lattitude = String.valueOf(latti);
  14. longitude = String.valueOf(longi);
  15. textView.setText(lattitude);
  16. textView1.setText(longitude);
  17. } else if (location1 != null) {
  18. double latti = location1.getLatitude();
  19. double longi = location1.getLongitude();
  20. lattitude = String.valueOf(latti);
  21. longitude = String.valueOf(longi);
  22. textView.setText(lattitude);
  23. textView1.setText(longitude);
  24. } else if (location2 != null) {
  25. double latti = location2.getLatitude();
  26. double longi = location2.getLongitude();
  27. lattitude = String.valueOf(latti);
  28. longitude = String.valueOf(longi);
  29. textView.setText(lattitude);
  30. textView1.setText(longitude);
  31. }else{
  32. Toast.makeText(this,"Unble to Trace your location",Toast.LENGTH_SHORT).show();
  33. }
  34. }
  35. }

更改后,sendcoordinates方法是:

  1. private boolean sendCoordinates(String terminalId, String lat, String lng) {
  2. HttpURLConnection con = null;
  3. try {
  4. URL obj = new URL("http://192.168.0.102:8085/position/send");
  5. con = (HttpURLConnection) obj.openConnection();
  6. con.setRequestMethod("POST");
  7. con.setRequestProperty("User-Agent", "Mozilla/5.0");
  8. con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
  9. con.setDoOutput(true);
  10. OutputStream os = con.getOutputStream();
  11. os.write(String.format(STATIC_LOCATION, terminalId, lat, lng).getBytes());
  12. os.flush();
  13. os.close();
  14. int responseCode = con.getResponseCode();
  15. if (responseCode == HttpURLConnection.HTTP_OK) { //success
  16. BufferedReader in = new BufferedReader(new InputStreamReader(
  17. con.getInputStream()));
  18. String inputLine;
  19. StringBuilder response = new StringBuilder();
  20. while ((inputLine = in.readLine()) != null) {
  21. response.append(inputLine);
  22. }
  23. in.close();
  24. return true;
  25. } else {
  26. return false;
  27. }
  28. } catch (Exception e) {
  29. // e.printStackTrace();
  30. return false;
  31. } finally {
  32. if (con != null) {
  33. con.disconnect();
  34. }
  35. }
  36. }

最后,onclick方法是:

  1. @Override
  2. public void onClick(View v) {
  3. locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  4. if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
  5. buildAlertMessageNoGps();
  6. } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
  7. getLocation();
  8. }
  9. executor.execute(new Runnable() {
  10. public void run() {
  11. Message msg = msgHandler.obtainMessage();
  12. // use MAC addr or IMEI as terminal id
  13. // read true position
  14. // replace static coordinates with the ones from the true position
  15. lat1=textView.getText().toString();
  16. long1=textView1.getText().toString();
  17. msg.arg1 = sendCoordinates("999999", lat1, long1) ? 1 : 0;
  18. msgHandler.sendMessage(msg);
  19. }
  20. });
  21. }
展开查看全部

相关问题