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

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

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

public class SendActivity extends AppCompatActivity implements View.OnClickListener {
    private Executor executor = Executors.newFixedThreadPool(1);
    private LocationManager locationManager;
    private String provider;
    private static final int REQUEST_LOCATION = 1;
    TextView textView;
    private volatile Handler msgHandler;

    private static final String STATIC_LOCATION =
            "{" +
                    "\"terminalId\":\"%s\"," +
                    "\"latitude\":\"%s\"," +
                    "\"longitude\":\"%s\"" +
                    "}";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send);

        textView = (TextView) findViewById(R.id.text_location);

        Button sendButton = findViewById(R.id.button_location);
        sendButton.setOnClickListener(this);

        msgHandler = new MsgHandler(this);

    }

    public void onClick(View v) {
        executor.execute(new Runnable() {
            public void run() {
                Message msg = msgHandler.obtainMessage();
                // use MAC addr or IMEI as terminal id
                // read true position
                // replace static coordinates with the ones from the true position
                 msg.arg1 = sendCoordinates("123456", "23.25", "45.02") ? 1 : 0;
                msgHandler.sendMessage(msg);

            }

        });
    }

    private boolean sendCoordinates(String terminalId, String lattitude, String longitude) {
        HttpURLConnection con = null;
        try {

            if (ActivityCompat.checkSelfPermission(SendActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                    (SendActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(SendActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

            } else {
                Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                Location location2 = locationManager.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER);

                if (location != null) {
                    double latti = location.getLatitude();
                    double longi = location.getLongitude();
                    lattitude = String.valueOf(latti);
                    longitude = String.valueOf(longi);

                    textView.setText("Your current location is"+ "\n" + "Lattitude = " + lattitude
                            + "\n" + "Longitude = " + longitude);

                } else  if (location1 != null) {
                    double latti = location1.getLatitude();
                    double longi = location1.getLongitude();
                    lattitude = String.valueOf(latti);
                    longitude = String.valueOf(longi);

                    textView.setText("Your current location is"+ "\n" + "Lattitude = " + lattitude
                            + "\n" + "Longitude = " + longitude);

                } else  if (location2 != null) {
                    double latti = location2.getLatitude();
                    double longi = location2.getLongitude();
                    lattitude = String.valueOf(latti);
                    longitude = String.valueOf(longi);

                    textView.setText("Your current location is"+ "\n" + "Lattitude = " + lattitude
                            + "\n" + "Longitude = " + longitude);

                }else{

                    Toast.makeText(this,"Unble to Trace your location",Toast.LENGTH_SHORT).show();

                }
            }

            URL obj = new URL("http://192.168.0.102:8085/position/send");
            con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

            con.setDoOutput(true);
            OutputStream os = con.getOutputStream();
            os.write(String.format(STATIC_LOCATION, terminalId, lattitude, longitude).getBytes());
            os.flush();
            os.close();

            int responseCode = con.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) { //success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        con.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }

                in.close();

                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
//            e.printStackTrace();
            return false;
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
    }

    private static class MsgHandler extends Handler {
        private final WeakReference<Activity> sendActivity;

        public MsgHandler(Activity activity) {
            sendActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (msg.arg1 == 1) {
                Toast.makeText(sendActivity.get().getApplicationContext(),
                        "Success!", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(sendActivity.get().getApplicationContext(),
                        "Error!", Toast.LENGTH_LONG).show();
            }
        }
    }
}

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

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

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

hfyxw5xn

hfyxw5xn1#

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

private Executor executor = newFixedThreadPool(1);

更确切地说,在methon:

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

在线程中调用:

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

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

private void getLocation() {
        if (ActivityCompat.checkSelfPermission(SendActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                (SendActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(SendActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

        } else {
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            Location location2 = locationManager.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER);

            if (location != null) {
                double latti = location.getLatitude();
                double longi = location.getLongitude();
                lattitude = String.valueOf(latti);
                longitude = String.valueOf(longi);

                textView.setText(lattitude);
                textView1.setText(longitude);

            } else  if (location1 != null) {
                double latti = location1.getLatitude();
                double longi = location1.getLongitude();
                lattitude = String.valueOf(latti);
                longitude = String.valueOf(longi);

                textView.setText(lattitude);
                textView1.setText(longitude);

            } else  if (location2 != null) {
                double latti = location2.getLatitude();
                double longi = location2.getLongitude();
                lattitude = String.valueOf(latti);
                longitude = String.valueOf(longi);

                textView.setText(lattitude);
                textView1.setText(longitude);

            }else{

                Toast.makeText(this,"Unble to Trace your location",Toast.LENGTH_SHORT).show();

            }
        }
    }

更改后,sendcoordinates方法是:

private boolean sendCoordinates(String terminalId, String lat, String lng) {
        HttpURLConnection con = null;
        try {
            URL obj = new URL("http://192.168.0.102:8085/position/send");
            con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

            con.setDoOutput(true);
            OutputStream os = con.getOutputStream();
            os.write(String.format(STATIC_LOCATION, terminalId, lat, lng).getBytes());
            os.flush();
            os.close();

            int responseCode = con.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) { //success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        con.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }

                in.close();

                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
//            e.printStackTrace();
            return false;
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
    }

最后,onclick方法是:

@Override
public void onClick(View v) {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps();

    } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        getLocation();
    }
    executor.execute(new Runnable() {
        public void run() {
            Message msg = msgHandler.obtainMessage();
            // use MAC addr or IMEI as terminal id
            // read true position
            // replace static coordinates with the ones from the true position
            lat1=textView.getText().toString();
            long1=textView1.getText().toString();
            msg.arg1 = sendCoordinates("999999", lat1, long1) ? 1 : 0;
            msgHandler.sendMessage(msg);

        }

    });
}

相关问题