使用下面的代碼,我能夠使用Nanohttpd輕量級服務器在android手機上創建移動服務器。該代碼基本上循環通過主機android設備的根目錄並列出文件和文件夾作爲鏈接。我想要實現的是,當用戶點擊任何鏈接(文件夾鏈接)時,瀏覽器應顯示包含在點擊文件夾鏈接中的文件和文件夾。我如何做到這一點,因爲我找不到任何Nanohttpd文檔的初學者。使用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);
}
}
}
:
您是否只想將文件夾名稱作爲鏈接? –
如圖所示,如果任何鏈接應該被點擊,如果它是一個文件夾,則應打開一個新頁面,顯示包含在被點擊文件夾中的文件和子文件夾。 –