Reputation: 941
I tried to get nanohttpd working under android. I have used this example:
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);
}
}
}
When i start the application on my phone the activity shows the proper ip address. I also can ping the shown address. But when i try to access this via a browser the site will not load. In addition the the above shown MainActivity.java i have only added the NanoHTTPD.java file from the nanohttpd project. Any ideas?
Upvotes: 3
Views: 2931
Reputation: 1141
Two things come to mind, both are permissions related. Take a look at your android manifest, you'll want two permissions for your app
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
INTERNET, because you're accessing network services, and WRITE_EXTERNAL_STORAGE because when NanoHttpd receives an incoming connection it writes temp files and most / all phones map the "java.io.tmpdir" to point at the SD card.
See if that helps.
Upvotes: 7