Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

兩台 Android 裝置透過伺服器轉發完成通訊的簡易 Demo

編輯:關於 Android 程式設計

這個 Demo 想解決的是內網裝置之間的通訊問題。基本思路:以 servlet 伺服器作為中繼站負責資料轉發,Android 端則用常駐服務搭配定時器「模擬」長連線——每隔一段時間主動向伺服器拉一次狀態。兩台手機因此得以互相傳遞資料。

整體架構

  • 終端(被監控端):開機後啟動一個 Service,定期以 HTTP 向伺服器查詢狀態。若伺服器回覆「開啟 GPS 收集」,就順勢拉起裝置上已安裝的 GPS 收集 App,並持續以 GET 方式把座標回報給伺服器。
  • 伺服器:以數個 servlet 分別處理狀態切換、資料寫入與查詢。
  • 控制端:發送幾個 GET 請求下達指令,程式碼很簡單,這裡不展開。

一、終端:定時輪詢的常駐服務

public class RunningServiceByPowerOn extends Service {

    private SharedPreferences mPreferences;

    @Override
    public IBinder onBind(Intent intent) { return null; }

    @Override
    public void onCreate() {
        super.onCreate();
        mPreferences = getSharedPreferences("Config", MODE_PRIVATE);
        timerTaskforGpsSwitch();
    }

    /** 每 5 秒查詢一次伺服器狀態 */
    private void timerTaskforGpsSwitch() {
        Timer timer = new Timer();
        Date d2 = new Date(System.currentTimeMillis());
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                String spec = "https://" + ConentValues.serverIp
                        + ":8080/MyServer/StartAction?mAction=find_gps_switcher1";
                try {
                    URL url = new URL(spec);
                    String str = HttpToServierUtils.connect(url);

                    if (str != null && str.equals("GPS_start")) {
                        // 收到指令,拉起 GPS 收集 App
                        if (mPreferences.getBoolean("isStop", true)) {
                            Intent intent = new Intent(Intent.ACTION_MAIN);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.addCategory(Intent.CATEGORY_LAUNCHER);
                            ComponentName cn = new ComponentName(
                                    "com.yqq.gpsinfolocationstartreceiver",
                                    "com.yqq.gpsinfolocationstartreceiver.MainActivity");
                            intent.setComponent(cn);
                            startActivity(intent);
                            mPreferences.edit().putBoolean("isStop", false).commit();
                        }
                    }
                    if (str != null && str.equals("GPS_stop")) {
                        mPreferences.edit().putBoolean("isStop", true).commit();
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        }, d2, 5000);
    }
}

二、GPS 收集服務

這個 Service 透過 LocationManager 取得位置,回呼中再用 AsyncTask 把座標送到伺服器:

public class GpsInfoCollectionService extends Service {

    private GPSinfoDao mGpSinfoDao;
    private LocationManager mLocationManager;
    private Location mLocation;
    private Criteria criteria;
    private String provider;

    @Override
    public IBinder onBind(Intent intent) { return null; }

    @Override
    public void onCreate() {
        super.onCreate();
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(true);
        criteria.setBearingRequired(true);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        criteria.setSpeedRequired(true);

        // GPS 未開啟時,引導使用者去系統設定
        if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "請開啟 GPS 導航...", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }

        mGpSinfoDao = new GPSinfoDao(getApplicationContext());
        timerTaskforGpsSwitch();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        provider = mLocationManager.getBestProvider(criteria, true);
        mLocationManager.requestLocationUpdates(provider, 300, 0.01f, new LocationListener() {
            @Override public void onStatusChanged(String p, int s, Bundle e) {}
            @Override public void onProviderEnabled(String p) {}
            @Override public void onProviderDisabled(String p) {}

            @Override
            public void onLocationChanged(Location location) {
                if (location == null) return;
                mLocation = location;

                new AsyncTask<Void, Void, Void>() {
                    private String str = null;

                    @Override
                    protected Void doInBackground(Void... params) {
                        String height = mLocation.getAltitude() + "";
                        String longitude = mLocation.getLongitude() + "";
                        String latitude = mLocation.getLatitude() + "";
                        String name = "Test";
                        String spec = "https://" + ConentValues.serverIp
                                + ":8080/MyServer/MyTest?longitude=" + longitude
                                + "&latitude=" + latitude
                                + "&height=" + height
                                + "&name=" + name;
                        try {
                            URL url = new URL(spec);
                            str = HttpToServierUtils.connect(url);
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        Toast.makeText(getApplicationContext(), str, 0).show();
                    }
                }.execute();
            }
        });
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        mGpSinfoDao = null;
        mLocationManager = null;
        mLocation = null;
        super.onDestroy();
    }

    /** 每 5 秒確認是否該停止收集 */
    private void timerTaskforGpsSwitch() {
        Timer timer = new Timer();
        Date d2 = new Date(System.currentTimeMillis());
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                String spec = "https://" + ConentValues.serverIp
                        + ":8080/MyServer/MyTest?mAction=find_gps_switcher";
                try {
                    URL url = new URL(spec);
                    String str = HttpToServierUtils.connect(url);
                    if (str != null && str.equals("GPS_stop")) {
                        stopSelf();
                        System.exit(0);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        }, d2, 5000);
    }
}

三、伺服器端 servlet

狀態查詢與資料寫入

public class MyTest extends HttpServlet {
    private GpsInfo info;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();

        String longitude = req.getParameter("longitude");
        String latitude = req.getParameter("latitude");
        String height = req.getParameter("height");
        String name = req.getParameter("name");
        String mAction = req.getParameter("mAction");

        // 定時器查詢開關狀態
        if (mAction != null && mAction.equals("find_gps_switcher")) {
            String result = DbUtis.getGPSStaus();
            if (result != null && result.equals("start_gps")) {
                out.write("GPS_start");
                out.flush();
            }
            if (result != null && result.equals("end_gps")) {
                out.write("GPS_stop");
                out.flush();
            }
        }

        // 寫入上傳的座標
        if (longitude != null && latitude != null && height != null) {
            info = new GpsInfo();
            info.setLongitude(longitude);
            info.setLatitude(latitude);
            info.setHeight(height);
            info.setName(name);
            DbUtis.insertGpsInfos(info);
            out.write("GPS 資料已上傳到伺服器");
            out.flush();
        }
    }
}

開關指令

/** 處理 GPS 開關狀態的 servlet */
public class GpsOnOffAction extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String gpsSend = req.getParameter("namegpsend");    // 開啟
        String gpsstop = req.getParameter("namegpsstop");   // 關閉
        PrintWriter out = resp.getWriter();

        if (gpsSend != null && gpsSend.equals("start_gps")) {
            out.write("終端 GPS 資訊收集開啟");
            DbUtis.deleteGpsSatus();
            DbUtis.insertGpsSatus("start_gps");
        } else if (gpsstop != null && gpsstop.equals("end_gps")) {
            out.write("終端 GPS 資訊收集關閉");
            DbUtis.deleteGpsSatus();
            DbUtis.insertGpsSatus("end_gps");
        }
        out.flush();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }
}

軌跡查詢(回傳 JSON)

/** 查詢 GPS 軌跡 */
public class QurAction extends HttpServlet {

    private JSONArray infos;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String s = req.getParameter("namereq");
        PrintWriter out = resp.getWriter();

        if (s != null) {
            infos = DbUtis.getData(s);
            out.write(infos.toString());
            out.flush();
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }
}

四、資料庫工具類別

DbUtis 負責 MySQL 連線與 CRUD,這裡列出幾個關鍵方法(連線字串與帳密請依環境調整,切勿把正式憑證寫死在原始碼中):

public class DbUtis {

    private static String ip = "192.168.1.134";
    private static Connection conn;

    /** 查詢軌跡,組裝成 JSON 陣列 */
    public static JSONArray getData(String name) throws SQLException {
        JSONArray array = new JSONArray();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://" + ip + ":3306/test", "root", "admin");
            String sql = "select name,longitude,latitude from gpsinfos where name=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, name);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name", rs.getString("name"));
                jsonObject.put("longitude", rs.getString("longitude"));
                jsonObject.put("latitude", rs.getString("latitude"));
                array.put(jsonObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) conn.close();
        }
        return array;
    }

    /** 讀取目前的 GPS 開關狀態 */
    public static String getGPSStaus() throws SQLException {
        String result = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://" + ip + ":3306/test", "root", "admin");
            pstmt = conn.prepareStatement("select gps_staus from gps_switcher");
            rs = pstmt.executeQuery();
            while (rs.next()) {
                result = rs.getString("gps_staus");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) conn.close();
        }
        return result;
    }

    /** 寫入一筆座標 */
    public static void insertGpsInfos(GpsInfo info) throws SQLException {
        PreparedStatement pstmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://" + ip + ":3306/test", "root", "admin");
            String sql = "insert into gpsinfos (name,longitude,latitude) values (?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, info.getName());
            pstmt.setString(2, info.getLongitude());
            pstmt.setString(3, info.getLatitude());
            pstmt.execute();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (pstmt != null) pstmt.close();
            if (conn != null) conn.close();
        }
    }

    /** 更新開關狀態 */
    public static void insertGpsSatus(String staus) throws SQLException {
        PreparedStatement pstmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://" + ip + ":3306/test", "root", "admin");
            pstmt = conn.prepareStatement("insert into gps_switcher (gps_staus) values (?)");
            pstmt.setString(1, staus);
            pstmt.execute();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (pstmt != null) pstmt.close();
            if (conn != null) conn.close();
        }
    }

    /** 清空開關狀態 */
    public static void deleteGpsSatus() throws SQLException {
        PreparedStatement pstmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://" + ip + ":3306/test", "root", "admin");
            pstmt = conn.prepareStatement("delete from gps_switcher");
            pstmt.execute();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (pstmt != null) pstmt.close();
            if (conn != null) conn.close();
        }
    }
}

五、控制端請求清單

// 終端查詢是否該啟動收集
https://{serverIp}:8080/MyServer/StartAction?mAction=find_gps_switcher1

// GPS 服務查詢是否該停止
https://{serverIp}:8080/MyServer/MyTest?mAction=find_gps_switcher

// 上報座標
https://{serverIp}:8080/MyServer/MyTest?longitude=111&latitude=222&height=1000&name=Test

// 查詢軌跡
https://{serverIp}:8080/MyServer/MyTest?namereq=Test

這個 Demo 的局限

值得誠實指出幾點。輪詢式「模擬長連線」在實務上問題不少:5 秒一次的高頻請求既耗電又耗流量,在真實網路環境下也很容易被系統的 Doze 模式與背景執行限制掐斷。若要正式上線,應改用 Firebase Cloud Messaging 這類推送服務,或自行維持 TCP/WebSocket 長連線並處理心跳與斷線重連。

此外,把資料庫帳密寫在 servlet 原始碼中、用 GET 傳座標、以 System.exit(0) 結束服務,都是不建議帶進正式環境的寫法。將它當作理解「裝置—伺服器—裝置」資料流的教學範例,價值/), 但別直接搬上 production。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved