使用下面的代码,我能够使用 Nanohttpd 轻量级服务器在 android 手机上创建移动服务器。该代码基本上循环通过主机android设备的根目录并将文件和文件夹列为链接。我要实现的是当用户单击任何链接(文件夹链接)时,浏览器应显示单击的文件夹链接中包含的文件和文件夹。我该怎么做,因为我找不到任何适合初学者的 Nanohttpd 文档。
import java.io.File;
import java.util.Map;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final int PORT = 8080;
private TextView hello;
private WebServer server;
private Handler handler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hello = (TextView) findViewById(R.id.hello);
}
/*
* There are some earlier versions of android that can not implement this
* method of getting IP address and isEmpty() method. The
*
* @SupreesLint("NewAPI") helps to suppress the error that will arise in
* such devices when implementing these methods . For the application
* however, a minimum version of API that can be able to execute the
* application flawlessly is set. The enables error checking as lower
* version that can not implement this methods wouldn't be able to install
* the application.
*/
@SuppressLint("NewApi")
@Override
protected void onResume() {
super.onResume();
TextView textIpaddr = (TextView) findViewById(R.id.ipaddr);
if (Utils.getIPAddress(true).trim().isEmpty()) {
textIpaddr.setText(Utils.getIPAddress(false) + ":" + PORT);
} else {
textIpaddr.setText(Utils.getIPAddress(true) + ":" + PORT);
}
try {
server = new WebServer();
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public String intToIp(int i) {
return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "."
+ ((i >> 8) & 0xFF) + "." + (i & 0xFF);
}
@Override
protected void onPause() {
super.onPause();
if (server != null)
server.stop();
}
private class WebServer extends NanoHTTPD {
public WebServer() {
super(8080);
}
@Override
public Response serve(String uri, Method method,
Map<String, String> header, Map<String, String> parameters,
Map<String, String> files) {
File rootDir = Environment.getExternalStorageDirectory();
File[] files2 = rootDir.listFiles();
String answer = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>sdcard0 - TECNO P5 - WiFi File Transfer Pro</title>";
for (File detailsOfFiles : files2) {
answer += "<a href=\"" + detailsOfFiles.getAbsolutePath()
+ "\" alt = \"\">" + detailsOfFiles.getAbsolutePath()
+ "</a><br>";
}
answer += "</head></html>";
return new NanoHTTPD.Response(answer);
}
}
}
: