欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android 服務端將位置信息發(fā)送給客戶端的實現(xiàn)

 更新時間:2021年01月25日 09:50:56   作者:歐陽子遙  
這篇文章主要介紹了Android 服務端將位置信息發(fā)送給客戶端的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

一、問題

Android 服務端將位置信息發(fā)送給客戶端

二、環(huán)境

AndroidStudio Eclipse

三、代碼實現(xiàn)

服務端Servlet調用Dao層在數(shù)據(jù)庫中查找數(shù)據(jù),在servlet中將查找到的數(shù)據(jù)匯集成json字符串(json數(shù)組形式)。

服務端:

 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("連接成功");
// PrintWriter printWriter = response.getWriter();
// printWriter.print("客戶端你好,數(shù)據(jù)連接成功!");
// printWriter.flush();
// printWriter.close();
 }

客戶端:

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));//設置請求參數(shù)項
          HttpClient httpClient = new DefaultHttpClient();
          HttpResponse httpResponse = httpClient.execute(httpRequest);//執(zhí)行請求返回響應
          if (httpResponse.getStatusLine().getStatusCode() == 200) {//判斷是否請求成功
            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, "沒有獲取到Android服務器端的響應!", Toast.LENGTH_LONG).show();
          }
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    });

請求地址書寫形式:http://主機IP地址:端口號/項目名/action名

HttpPost方式建立連接,HttpResponse.getEntity()獲取響應信息,EntityUtils.toString(entity, “UTF-8”)將entity轉為String字符串,Intent將JSON字符串傳遞到其他activity頁面中去。

JSON字符串解析類:

public static List<Address> getAddress(String jsonStr)
      throws JSONException {
    /******************* 解析 ***********************/
    // 初始化list數(shù)組對象
    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;
  }

我這個是當時在做一個兒童定位寫的,數(shù)據(jù)庫設計沒思考全面,思維比較狹隘。

應該思考到的是兒童信息表中兒童信息要跟父母表中父母信息對應起來,即這APP是給多對父母和孩子使用的,而不是一對父母與孩子。

服務端也不應該是使用本地的,應該使用云服務器,這樣就不會被同一局域網(wǎng)所限制。

Android 客戶端將位置信息發(fā)送給服務端

代碼實現(xiàn)

客戶端:

 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));//設置請求參數(shù)項
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse = httpClient.execute(httpRequest);//執(zhí)行請求返回響應
        if(httpResponse.getStatusLine().getStatusCode() == 200){//判斷是否請求成功
//          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, "沒有獲取到Android服務器端的響應!", Toast.LENGTH_LONG).show();
          Intent intent = new Intent();
          intent.setAction("cn.abel.action.broadcast");
          intent.putExtra("Response", "沒有獲取到Android服務器端的響應!");
          context.sendBroadcast(intent);
        }
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
params.add(new BasicNameValuePair(“Time”, str));

Time是str的變量名,用于服務端接收數(shù)據(jù)用的。
這是用來添加要傳遞給服務端的數(shù)據(jù),為String字符串形式。

服務端:

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("客戶端你好,數(shù)據(jù)連接成功!");
 printWriter.flush();
 printWriter.close();
 }

request.getParameter(“變量名”)是用來接收客戶端對應變量名的數(shù)據(jù)。
addressDao.insert()是我自己定義的方法,將接收到的數(shù)據(jù)存入MySQL中。

到此這篇關于Android 服務端將位置信息發(fā)送給客戶端的實現(xiàn)的文章就介紹到這了,更多相關Android 服務端位置信息發(fā)送給客戶端內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Kotlin協(xié)程Job生命周期結構化并發(fā)詳解

    Kotlin協(xié)程Job生命周期結構化并發(fā)詳解

    這篇文章主要為大家介紹了Kotlin協(xié)程Job生命周期結構化并發(fā)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-12-12
  • Android Studio中使用lambda表達式的方法

    Android Studio中使用lambda表達式的方法

    這篇文章主要介紹了Android Studio中使用lambda表達式的方法,需要的朋友可以參考下
    2017-06-06
  • Android中巧妙的實現(xiàn)緩存詳解

    Android中巧妙的實現(xiàn)緩存詳解

    采用緩存,可以進一步大大緩解數(shù)據(jù)交互的壓力,有的時候為了快速查詢會被多次調用的數(shù)據(jù),或者構建比較廢時的實例,我們一般使用緩存的方法。無論大型或小型應用,靈活的緩存可以說不僅大大減輕了服務器的壓力,而且因為更快速的用戶體驗而方便了用戶。下面來一起看看吧。
    2016-11-11
  • Android實現(xiàn)讀取相機(相冊)圖片并進行剪裁

    Android實現(xiàn)讀取相機(相冊)圖片并進行剪裁

    在 Android應用中,很多時候我們需要實現(xiàn)上傳圖片,或者直接調用手機上的拍照功能拍照處理然后直接顯示并上傳功能,下面將講述調用相機拍照處理圖片然后顯示和調用手機相冊中的圖片處理然后顯示的功能
    2015-08-08
  • Android自定義View實現(xiàn)帶4圓角或者2圓角的效果

    Android自定義View實現(xiàn)帶4圓角或者2圓角的效果

    這篇文章主要介紹了Android自定義View實現(xiàn)帶4圓角或者2圓角的效果,本文通過實例代碼截圖給大家展示的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-03-03
  • Android仿微信照片選擇器實現(xiàn)預覽查看圖片

    Android仿微信照片選擇器實現(xiàn)預覽查看圖片

    這篇文章主要介紹了Android仿微信照片選擇器實現(xiàn)預覽查看圖片的相關資料,感興趣的小伙伴們可以參考一下
    2016-01-01
  • Android中使用Alarm的方法小結

    Android中使用Alarm的方法小結

    Alarm是android提供的用于完成鬧鐘式定時任務的類,系統(tǒng)通過AlarmManager來管理所有的Alarm,下面這篇文章主要給大家介紹了關于Android中使用Alarm的相關資料,需要的朋友可以參考下。
    2017-05-05
  • android獲取時間差的方法

    android獲取時間差的方法

    這篇文章主要介紹了android獲取時間差的方法,涉及Android操作時間的相關技巧,需要的朋友可以參考下
    2015-04-04
  • Android Studio ADB網(wǎng)絡調試匯總

    Android Studio ADB網(wǎng)絡調試匯總

    這篇文章主要為大家詳細介紹了Android Studio ADB網(wǎng)絡調試的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-05-05
  • Android?Flutter實現(xiàn)彈簧動畫交互的示例詳解

    Android?Flutter實現(xiàn)彈簧動畫交互的示例詳解

    物理模擬可以讓應用程序的交互感覺逼真和互動,本文章實現(xiàn)了演示了如何使用彈簧模擬將小部件從拖動的點移回中心,感興趣的可以了解一下
    2023-04-04

最新評論