You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android设备特定端口暴露本地WebService?

Android本机后台Web服务最简实现方案

要实现仅本机可访问的后台Web服务,返回指定JSON,最简方案是使用NanoHTTPD——一个轻量级的嵌入式HTTP服务器库,无需复杂配置即可快速搭建。以下是完整实现步骤:

1. 添加依赖

在app/build.gradle的dependencies块中引入NanoHTTPD:

implementation 'org.nanohttpd:nanohttpd:2.3.1'

2. 实现自定义HTTP服务器

创建继承自NanoHTTPD的类,重写serve方法返回目标JSON,同时绑定127.0.0.1确保仅本机访问:

public class LocalWebServer extends NanoHTTPD {

    public LocalWebServer() {
        // 绑定本机地址和指定端口
        super("127.0.0.1", 123456);
    }

    @Override
    public Response serve(IHTTPSession session) {
        // 返回要求的JSON响应
        String jsonContent = "{\"message\": \"Hello world!\"}";
        // 设置响应头为JSON格式
        return newFixedLengthResponse(Response.Status.OK, "application/json", jsonContent);
    }
}

3. 后台Service托管服务器

为了让服务器在后台持续运行,创建Service类,并处理Android 8+的后台限制(使用前台服务):

public class WebServerService extends Service {
    private LocalWebServer webServer;

    @Override
    public void onCreate() {
        super.onCreate();
        try {
            webServer = new LocalWebServer();
            webServer.start();
            
            // Android 8+必须用前台服务避免被系统回收
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                // 创建通知渠道
                NotificationChannel channel = new NotificationChannel(
                        "web_server_channel",
                        "本地Web服务",
                        NotificationManager.IMPORTANCE_LOW
                );
                NotificationManager notificationManager = getSystemService(NotificationManager.class);
                if (notificationManager != null) {
                    notificationManager.createNotificationChannel(channel);
                }
                // 构建前台通知
                Notification notification = new NotificationCompat.Builder(this, "web_server_channel")
                        .setContentTitle("本地Web服务运行中")
                        .setContentText("监听地址:127.0.0.1:123456")
                        .setSmallIcon(R.drawable.ic_notification) // 替换为你的通知图标
                        .build();
                startForeground(1, notification);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 停止服务器
        if (webServer != null) {
            webServer.stop();
        }
    }

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

4. 配置清单与权限

在AndroidManifest.xml中注册Service并添加必要权限:

<!-- 前台服务权限 -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

<application ...>
    <!-- 注册后台服务 -->
    <service 
        android:name=".WebServerService" 
        android:exported="false" />
</application>

5. 启动服务

在Activity或其他入口处启动服务:

Intent serviceIntent = new Intent(this, WebServerService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    startForegroundService(serviceIntent);
} else {
    startService(serviceIntent);
}

后续扩展(针对xDrip模拟接口)

如果需要模拟xDrip的接口响应,只需修改LocalWebServer的serve方法,返回符合xDrip接口格式的JSON即可,无需改变整体架构。

内容的提问来源于stack exchange,提问作者m.antkowicz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 17:02:34