在 Android 上试试 NanoHttpd。 NanoHttpd 将作为 Android 上的服务器。
第 1 步:
下载NanoHTTPD.java。在你的项目中添加这个类。
创建一个Activity(HttpServerConnection)并添加以下代码:
public class HttpServerConnection extends Activity {
private WebServer server;
private static String TAG = "[HttpServerConnection]";
private static int default_server_port = 8005;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
// Init a server
server = new WebServer();
try {
server.start();
} catch (IOException ioe) {
Log.w(TAG, "The server could not start.");
ioe.printStackTrace();
}
Log.w(TAG, "================Web server initialized=============>");
}
// On destroy
@Override
public void onDestroy() {
super.onDestroy();
if (server != null) {
server.stop();
Log.w(TAG, "=================Web server stopped================>");
}
}
// Webserver class which extends the NanoHTTPD class
private class WebServer extends NanoHTTPD {
public WebServer() {
super(default_server_port);
}
/*
* Description : Function to run when a request message is triggered and
* the application needs to process it to send a response.
*/
@Override
public synchronized Response serve(String uri, Method method,
Map<String, String> header, Map<String, String> parameters,
Map<String, String> files) {
Log.w(TAG, "Request header details: " + header.toString());
// Extract the parameters and header (mobile number and the message)
// Send SMS using SmsManager
return null;
}
}
}
第 2 步:
将 HTTP 请求从 php 服务器推送到带有参数的 NanoHttpd 服务器。
第 3 步:
NanoHttpd 服务器将在函数 'serve' 中接收请求:
@Override
public synchronized Response serve(IHTTPSession session) {
}
第 4 步:
在“服务”函数中解析请求中的数据(消息和手机号码),并使用 SmsManager 类发送短信。
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number, null, message, null,
null);
我为我的工作做了类似的事情(我已经将它实现为 Android 服务),它就像一个魅力。
它非常容易上手,并且“NanoHttpd”服务器使用起来非常稳定。