用自己的Android手機做迷你簡訊機

來源:互聯網
上載者:User

標籤:android   webservice   簡訊   簡訊機   伺服器   

1、Android httpserver 和 http調試

Android http server  : httpcore

PC http client  : httpdebug


2、簡訊發送

Android內建的android.telephony.SmsManager包


3、源碼:


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;/** * Basic, yet fully functional and spec compliant, HTTP/1.1 file server. * <p> * Please note the purpose of this application is demonstrate the usage of * HttpCore APIs. It is NOT intended to demonstrate the most efficient way of * building an HTTP file server. *  *  */public class HttpServer {public static void start(String[] args) throws Exception {Thread t = new RequestListenerThread(8080);t.setDaemon(false);t.start();//start the webservice server}static class WebServiceHandler implements HttpRequestHandler {public WebServiceHandler() {super();}public void handle(final HttpRequest request,final HttpResponse response, final HttpContext context)throws HttpException, IOException {String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);//get uriString 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);// send smsString 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") ) {System.out.println("GET " + target);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") ){System.out.println("POST " + target);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 {// this.serversocket = new ServerSocket(port);System.out.println("RequestListenerThread start");// Set up the HTTP protocol processorHttpProcessor 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");// Set up request handlersHttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();reqistry.register("*", new WebServiceHandler());  //WebServiceHandler用來處理webservice請求。this.httpService = new HttpService(httpproc,new DefaultConnectionReuseStrategy(),new DefaultHttpResponseFactory());httpService.setParams(this.params);httpService.setHandlerResolver(reqistry);//為http服務設定註冊好的要求處理常式。}@Overridepublic void run() {System.out.println("Listening on port "+ this.serversocket.getLocalPort());System.out.println("Thread.interrupted = " + Thread.interrupted()); while (!Thread.interrupted()) {try {// Set up HTTP connectionSocket socket = this.serversocket.accept();DefaultHttpServerConnection conn = new DefaultHttpServerConnection();System.out.println("Incoming connection from "+ socket.getInetAddress());conn.bind(socket, this.params);// Start worker threadThread t = new WorkerThread(this.httpService, conn);t.setDaemon(true);t.start();} catch (InterruptedIOException ex) {break;} catch (IOException e) {System.err.println("I/O error initialising connection thread: "+ 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;}@Overridepublic void run() {System.out.println("New connection thread");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) {}}}}}

4、配置: 

    在AndroidManifest.xml裡添加許可權:

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

5、調用:  在activity裡調用Httpserver.start(null)就可以啟動了


6、測試:  httpdebug  發送測試樣本: http://192.168.1.101:8080/?mobile=12312341234&regcode=232423


7、遇到的問題:

1)筆記本和wifi同時使用無線網時,發現路由器禁用了無線網裝置互相通訊的功能,這個開啟AP隔離的配置需要去掉打鉤:


2)某派大神F1手機調用httpcore作為httpserver,運行時報錯:Library ‘libmaliinstr.so‘ not found。發現有人用這手機做別的也報這個錯,換一台手機後正常。看名字應該是Arm的Mali圖形硬體的相關庫



參考連結

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

用自己的Android手機做迷你簡訊機

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.