2013-07-16 32 views
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文件。有任何想法嗎?

回答

6

想到了兩件事情,兩者都與權限有關。在您的Android清單看一看,你會希望你的應用程序

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

INTERNET兩種權限,因爲你所訪問的網絡服務,並WRITE_EXTERNAL_STORAGE因爲當NanoHttpd接收寫入臨時文件傳入的連接和最/所有手機都將「java.io.tmpdir」映射到SD卡上。

看看是否有幫助。

+0

請看下面的內容https://stackoverflow.com/questions/36052956/live-camera-streaming-with-nanohttpd-in-android –