Implementation of Android Server Sending Location Information to Client

  • 2021-12-11 08:55:27
  • OfStack

1. Problems

The Android server sends the location information to the client

2. Environment

AndroidStudio Eclipse

3. Code implementation

The server Servlet calls the Dao layer to find data in the database, and aggregates the found data into an json string (json array form) in servlet.

Server side:


 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// response.setContentType("text/plain; charset=UTF-8");
 request.setCharacterEncoding("UTF-8");
 ServerToParentDao stpDao = new ServerToParentDao();
// String num = mtpDao.query();
// System.out.println(num);
 PrintWriter out = response.getWriter();
 StringBuffer sb = new StringBuffer();
 sb.append('[');
 List<Address> addrList = stpDao.queryOne();
 for (Address address : addrList) {
  sb.append('{').append("\"id\":").append("" + address.getId() + "").append(",");
  sb.append("\"latitude\":").append("\"" + address.getLatitude() + "\"").append(",");
  sb.append("\"longitude\":").append("\"" + address.getLongitude() + "\"").append(",");
  sb.append("\"time\":\"").append(address.getTime());
  sb.append("\"}").append(",");
 }
 sb.deleteCharAt(sb.length() - 1);
 sb.append(']');
 out.write(sb.toString());
 System.out.println(sb.toString());
// request.setAttribute("json",sb.toString());
// request.getRequestDispatcher("watch.jsp").forward(request, response);
// out.write(num);
//  response.getOutputStream().write(mtpDao.query().getBytes("UTF-8"));
 out.flush();
 out.close();

// System.err.println(request.getParameter(""));
//  System.out.println(code);
 System.out.println(" Connection succeeded ");
// PrintWriter printWriter = response.getWriter();
// printWriter.print(" Hello client, the data connection is successful! ");
// printWriter.flush();
// printWriter.close();
 }

Client:


sendButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        HttpPost httpRequest = new HttpPost("http://192.168.159.1:8080/MyAndroidServer/ServerToParentServlet");
        List<NameValuePair> params = new ArrayList<NameValuePair>();
//        String str = "1";
//        params.add(new BasicNameValuePair("Code", str));
        Log.i("MY3", "Has Done");
        try {
//          httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));// Setting Request Parameter Items 
          HttpClient httpClient = new DefaultHttpClient();
          HttpResponse httpResponse = httpClient.execute(httpRequest);// Execute a request and return a response 
          if (httpResponse.getStatusLine().getStatusCode() == 200) {// Determine whether the request was successful 
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
              System.out.println("---------");
//              System.out.println("Respone content" + EntityUtils.toString(entity, "UTF-8"));
              Intent intent = new Intent(ParentRequest.this,MainActivity.class);
              intent.putExtra("jsonString",EntityUtils.toString(entity, "UTF-8"));
              startActivity(intent);
            }
        Log.i("MY2", "Has Done");
          } else {
            Toast.makeText(ParentRequest.this, " Not retrieved Android Server-side response! ", Toast.LENGTH_LONG).show();
          }
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    });

Request address writing form: http://Host IP Address: Port number/Project name/action name

The connection is established in HttpPost mode, HttpResponse. getEntity () obtains response information, EntityUtils. toString (entity, "UTF-8") converts entity into String string, and Intent passes JSON string to other activity pages.

JSON string parsing class:


public static List<Address> getAddress(String jsonStr)
      throws JSONException {
    /*******************  Analyse  ***********************/
    //  Initialization list Array object 
    List<Address> mList = new ArrayList<Address>();
    Address address = new Address();
    JSONArray array = new JSONArray(jsonStr);
    for (int i = 0; i < array.length(); i++) {
      JSONObject jsonObject = array.getJSONObject(i);
      address = new Address(jsonObject.getInt("id"),
          jsonObject.getString("latitude"), jsonObject.getString("longitude"),
          jsonObject.getString("time"));
      mList.add(address);
    }
    return mList;
  }

I was doing a child positioning at that time. The database design was not comprehensive and my thinking was narrow.

It should be considered that the children's information in the children's information table should correspond to the parents' information in the parents' table, that is, this APP is for many pairs of parents and children, not one pair of parents and children.

The server should not be local, but should use a cloud server, so that it will not be limited by the same LAN.

The Android client sends location information to the server

Code implementation

Client:


 HttpPost httpRequest = new HttpPost("http://192.168.159.1:8080/MyAndroidServer/ChildrenToServerServlet");
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
      Date date = new Date(System.currentTimeMillis());
      String str=simpleDateFormat.format(date);
      System.out.println(str);
      params.add(new BasicNameValuePair("Time", str));
      params.add(new BasicNameValuePair("Latitude",latitude));
      params.add(new BasicNameValuePair("Longitude", longitude));
      try {
        httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));// Setting Request Parameter Items 
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse = httpClient.execute(httpRequest);// Execute a request and return a response 
        if(httpResponse.getStatusLine().getStatusCode() == 200){// Determine whether the request was successful 
//          Toast.makeText(ChildrenToServerActivity.this, EntityUtils.toString(httpResponse.getEntity()), Toast.LENGTH_LONG).show();
          Intent intent = new Intent();
          intent.setAction("cn.abel.action.broadcast");
          intent.putExtra("Response", EntityUtils.toString(httpResponse.getEntity()));
          context.sendBroadcast(intent);
        }else{
//          Toast.makeText(MainActivity.this, " Not retrieved Android Server-side response! ", Toast.LENGTH_LONG).show();
          Intent intent = new Intent();
          intent.setAction("cn.abel.action.broadcast");
          intent.putExtra("Response", " Not retrieved Android Server-side response! ");
          context.sendBroadcast(intent);
        }
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }

params.add(new BasicNameValuePair( " Time " , str));

Time is the variable name of str, which is used by the server to receive data.
This is used to add data to be passed to the server in the form of String string.

Server side:


public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
 response.setContentType("text/plain; charset=UTF-8");
 request.setCharacterEncoding("UTF-8");
 String time = request.getParameter("Time");
 String latitude = request.getParameter("Latitude");
 String longitude = request.getParameter("Longitude");
 ChildrenToAddressDao addressDao = new ChildrenToAddressDao();
 addressDao.insert(latitude, longitude, time);
 
 System.err.println(request.getParameter("Time"));
 System.err.println(request.getParameter("Latitude"));
 System.err.println(request.getParameter("Longitude"));
 PrintWriter printWriter = response.getWriter();
 printWriter.print(" Hello client, the data connection is successful! ");
 printWriter.flush();
 printWriter.close();
 }

request. getParameter ("variable name") is used to receive data corresponding to the variable name on the client.
addressDao. insert () is a self-defined method that stores the received data into MySQL.


Related articles: