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

把舊 Android 手機改造成迷你簡訊發送機

編輯:關於 Android 程式設計

家裡閒置的 Android 手機別急著丟,裝個 HTTP Server 就能變成一台可遠端呼叫的簡訊發送裝置——輸入驗證碼、發通知、做簡訊服務的測試樁都很合適。

技術選型

  • HTTP Server:Android 端使用 Apache HttpCore(org.apache.http)自行起一個 socket 服務。
  • HTTP 客戶端:PC 端用 HTTPDebug 這類工具發送測試請求即可。
  • 簡訊發送:使用 Android 自帶的 android.telephony.SmsManager。

核心程式碼

package com.example.httpservertest;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Locale;

import org.apache.http.ConnectionClosedException;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpServerConnection;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.DefaultHttpServerConnection;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
import org.apache.http.protocol.HttpService;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;

import android.telephony.SmsManager;

/**
 * 精簡但功能完整的 HTTP/1.1 服務,示範 HttpCore 的用法
 */
public class HttpServer {

    public static void start(String[] args) throws Exception {
        Thread t = new RequestListenerThread(8080);
        t.setDaemon(false);
        t.start();
    }

    static class WebServiceHandler implements HttpRequestHandler {

        public void handle(final HttpRequest request, final HttpResponse response,
                           final HttpContext context) throws HttpException, IOException {
            String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
            String target = request.getRequestLine().getUri();

            // 解析手機號與驗證碼
            String mobile = "86" + target.substring(target.indexOf("mobile") + 7,
                                                    target.indexOf("&"));
            String regcode = target.substring(target.indexOf("regcode") + 8);
            System.out.println("mobile " + mobile + " regcode " + regcode);

            // 發送簡訊
            String content = "【CSDN-lonelyrains】您的注冊驗證碼為:" + regcode;
            SmsManager smsManager = SmsManager.getDefault();
            List<String> texts = smsManager.divideMessage(content);
            for (String text : texts) {
                smsManager.sendTextMessage(mobile, null, text, null, null);
            }

            if (method.equals("GET")) {
                response.setStatusCode(HttpStatus.SC_OK);
                StringEntity entity = new StringEntity(
                        "<xml><method>get</method><url>" + target + "</url></xml>");
                response.setEntity(entity);
            } else if (method.equals("POST")) {
                response.setStatusCode(HttpStatus.SC_OK);
                StringEntity entity = new StringEntity(
                        "<xml><method>post</method><url>" + target + "</url></xml>");
                response.setEntity(entity);
            } else {
                throw new MethodNotSupportedException(method + " method not supported");
            }
        }
    }

    static class RequestListenerThread extends Thread {
        private final ServerSocket serversocket;
        private final HttpParams params;
        private final HttpService httpService;

        public RequestListenerThread(int port) throws IOException {
            HttpProcessor httpproc = new ImmutableHttpProcessor(
                    new HttpResponseInterceptor[] {
                            new ResponseDate(),
                            new ResponseServer(),
                            new ResponseContent(),
                            new ResponseConnControl()
                    });

            this.params = new BasicHttpParams();
            this.params
                    .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
                    .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
                    .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
                    .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
                    .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");

            HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
            reqistry.register("*", new WebServiceHandler());

            this.httpService = new HttpService(httpproc,
                    new DefaultConnectionReuseStrategy(),
                    new DefaultHttpResponseFactory());
            httpService.setParams(this.params);
            httpService.setHandlerResolver(reqistry);
        }

        @Override
        public void run() {
            System.out.println("Listening on port " + this.serversocket.getLocalPort());
            while (!Thread.interrupted()) {
                try {
                    Socket socket = this.serversocket.accept();
                    DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
                    conn.bind(socket, this.params);
                    Thread t = new WorkerThread(this.httpService, conn);
                    t.setDaemon(true);
                    t.start();
                } catch (InterruptedIOException ex) {
                    break;
                } catch (IOException e) {
                    System.err.println("I/O error: " + e.getMessage());
                    break;
                }
            }
        }
    }

    static class WorkerThread extends Thread {
        private final HttpService httpservice;
        private final HttpServerConnection conn;

        public WorkerThread(final HttpService httpservice,
                            final HttpServerConnection conn) {
            super();
            this.httpservice = httpservice;
            this.conn = conn;
        }

        @Override
        public void run() {
            HttpContext context = new BasicHttpContext(null);
            try {
                while (!Thread.interrupted() && this.conn.isOpen()) {
                    this.httpservice.handleRequest(this.conn, context);
                }
            } catch (ConnectionClosedException ex) {
                System.err.println("Client closed connection");
            } catch (IOException ex) {
                System.err.println("I/O error: " + ex.getMessage());
            } catch (HttpException ex) {
                System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
            } finally {
                try {
                    this.conn.shutdown();
                } catch (IOException ignore) {
                }
            }
        }
    }
}

權限設定

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.SEND_SMS" />

啟動與測試

在 Activity 中呼叫 HttpServer.start(null) 即可啟動服務。測試時用 HTTPDebug 送出:

https://192.168.1.101:8080/?mobile=12312341234&regcode=232423

實作中遇到的問題

1. 筆電與手機互相找不到對方

無線網路看似連在同一個 AP 上,但請求就是不通。原因是路由器開啟了 AP 隔離(也稱用戶隔離),會阻擋同一網段內裝置彼此通訊。登入管理介面把這個選項取消勾選即可。

2. 特定機型啟動時報找不到函式庫

某款機型執行時出現 Library "libmaliinstr.so" not found,換一台機器就正常。從名稱看應與 ARM Mali 圖形硬體相關的廠商定製庫有關,屬於該 ROM 的問題。

安全提醒

這個示範把「發送簡訊」這個高風險能力直接暴露在一個毫無驗證的 HTTP 端點上,任何能連到該埠的人都可以任意發送簡訊。因此:

  • 請勿在公網或不可信網路上這樣使用。
  • 正式用途務必加上 Token 驗證、來源 IP 白名單與呼叫頻率限制。
  • 另外,Apache HttpClient 在 Android 5.0 之後已被標記為不再維護,新專案建議改用 HttpURLConnection 或 OkHttp,若要繼續用 HttpCore 則需自行以 Gradle 引入 org.apache.httpcomponents:httpcore。

參考連結

https://blog.csdn.net/jkeven/article/details/9271145

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