3
我試着在android下獲得nanohttpd。我用過這個例子:nanohttpd在android中不會工作
package com.example.android_test;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import com.example.android_test.NanoHTTPD.Response.Status;
import android.app.Activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final int PORT = 8765;
private TextView hello;
private MyHTTPD server;
private Handler handler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
hello = (TextView) findViewById(R.id.hello);
}
@Override
protected void onResume() {
super.onResume();
TextView textIpaddr = (TextView) findViewById(R.id.ipaddr);
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
final String formatedIpAddress = String.format("%d.%d.%d.%d", (ipAddress & 0xff),
(ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
textIpaddr.setText("Please access! http://" + formatedIpAddress + ":" + PORT);
try {
server = new MyHTTPD();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
super.onPause();
if (server != null)
server.stop();
}
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(PORT);
}
@Override
public Response serve(String uri, Method method, Map<String, String> headers,
Map<String, String> parms, Map<String, String> files) {
final StringBuilder buf = new StringBuilder();
for (Entry<String, String> kv : headers.entrySet())
buf.append(kv.getKey() + " : " + kv.getValue() + "\n");
handler.post(new Runnable() {
@Override
public void run() {
hello.setText(buf);
}
});
final String html = "<html><head><head><body><h1>Hello, World</h1></body></html>";
return new NanoHTTPD.Response(Status.OK, MIME_HTML, html);
}
}
}
當我在手機上啓動應用程序時,活動顯示正確的IP地址。我也可以ping顯示的地址。但是,當我嘗試通過瀏覽器訪問此網站將不會加載。另外,上面顯示的MainActivity.java我只添加了nanohttpd項目中的NanoHTTPD.java文件。有任何想法嗎?
請看下面的內容https://stackoverflow.com/questions/36052956/live-camera-streaming-with-nanohttpd-in-android –