我正在使用 WakefulBroadcastReceiver
方法创建一个作为 root
的服务,用于某些测试目的(请注意,我刚刚使用启动服务器的 Activity 进行了测试,同样的事情发生了):
MyService.java
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Server starting");
// Create the server
server = new WebServer(6666);
new Thread(new Runnable() {
@Override
public void run() {
try {
server.start();
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
}).start();
...
return START_STICKY;
}
WebServer.java:
public class WebServer extends NanoHTTPD {
@Override
public Response serve(IHTTPSession session) {
Log.d(TAG, "Serving");
return new NanoHTTPD.Response("<html><body>test</body></html>");
}
我使用 adb
在/system/app 中push
APK,以便无需先使用 Activity 即可调用该服务。然后重新启动 shell。
我可以看到服务器等待连接的日志,然后:
- 如果我使用
wget http://127.0.0.1:6666
使用adb shell
,我可以看到日志“Serving”。 - 如果我使用具有相同地址的设备浏览器(也尝试过
localhost
),则无法访问服务器。
我使用 API18 和默认的 Nexus7 AVD(也尝试使用 Genymotion
和三星平板电脑),但没有任何效果。网络设置中没有配置代理。
我不明白为什么浏览器(在设备上)无法访问我在 127.0.0.1
上的 6666
端口(也在设备上)
这是 list :
<application android:allowBackup="true" android:label="@string/app_name"
android:icon="@mipmap/ic_launcher" android:theme="@style/AppTheme">
<service android:name=".MyService" android:label="Tool" android:enabled="true"/>
<receiver android:name=".receiver.BootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
最佳答案
我快疯了,终于有人给我发了这个链接: https://superuser.com/questions/188058/which-ports-are-considered-unsafe-on-chrome
端口 6666 被认为是不安全的...我希望它能写在页面上,而不是无法到达服务器。
关于java - Android浏览器无法连接本地nanohttpd服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31074086/