Local Web Server with NanoHTTPD - android

I am trying to create a local web server using NanoHTTPD on Android. I know how to use it for a single file doing something like:
#Override
public Response serve(IHTTPSession session) {
String answer = "";
try {
FileReader index = new FileReader(fileLocation);
BufferedReader reader = new BufferedReader(index);
String line = "";
while ((line = reader.readLine()) != null) {
answer += line;
}
reader.close();
} catch(IOException ioe) {
Log.w("Httpd", ioe.toString());
}
return newFixedLengthResponse(answer);
}
and setting it to port 8080 so I can browse to http://localhost:8080 and view the file. However, I would like to use NanoHTTPD to put an entire directory on the server and not just a single file, in order to run an HTML5 game. Kinda similarly to how I can browse to a folder in Command Prompt on Windows and use
python -m http.server 4444
in order to browse through the folder as if it were a website at http://localhost:4444. I'm not sure how to go about it using NanoHTTPD. Can someone help me figure out where to start, or is there another library out there that's much easier to use?
Thanks in advance. Any help would be greatly appreciated.

You are on the right path.
Quick answer look here.
What you shod do is generate HTML files of directory structure to the user.
Meaning when the user is first contacting you read the local directory that you determine as root directory and create an HTML file as a response with the file names as links.
If the user then clicks on a single file serve it like you already do.
I found an answer demonstrating how to generate HTML files dynamically that you can use here.

Related

How to download zip file from url in unity?

I am using unity 2019.2.14f1 and visual studio 2019.I also tried with ICSharpCode.SharpZipLib but can't find any solution.I am trying with the code from the code which is available in the following url:
Unzip a memorystream (Contains the zip file) and get the files
Thanks in advance.
You can download files in Unity using UnityWebRequest.Get. Note that using it like in the example shown on that page, you're going to want to make sure you know how to use Unity's Coroutines.
Also, instead of downloadHandler.text you're going to want to use downloadHandler.data to get the downloaded data as bytes you can put into a stream.
Once you've got those you can use the appropriate libraries or standard library calls to unzip your files.
To download a file from a URL you can use system.net
WebClient client = new WebClient();
client.DownloadFile("http://whateverlinkyouhave.zip", #"C:\whateverlinkyouhave.zip")
Everyone's answer is correct, especially using UnityWebRequest. One of things you must do is to turn the byte[] data to zip file. And then use some Unzip library.
Example implementation
using System;
using UnityEngine.Networking;
private IEnumerator DownloadZipFile(string url)
{
using (UnityWebRequest www = UnityWebRequest.Get(url))
{
yield return www.Send();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
string savePath = string savePath = string.Format("{0}/{1}.zip", Application.persistentDataPath, "zip_file_name");
System.IO.File.WriteAllBytes(savePath, www.downloadHandler.data);
}
}
}
Hope it helps.

Getting Shared Preferences while Migrating Project from Cocos2dX to Unity Android

I had to port my game from Cocos2dX to Unity for various reasons.
I have now ported the project successfully but to launch it I have to make a mechanism to get old user data and store it in new structure, like number of levels locked, high score of users etc.
While searching I came to know that COCOS2dX stored data on user's device on following path
system/data/data/mygamepackage/shared_prefs/Cocos2dxPrefsFile.xml
Is there anyway to get data from above mentioned path?
The above path should be accessible by the app it self.
I am not able to read that file I get following error.
ENOENT No Such file or Directory
The file is there I can see that on rooted device via Root Browser but I get the error when I run the app on same device.
All I need is to access the file programmatically and later I will parse it and will store it via Unity for future use.
Looking forward for a positive and quick response.
I dont know why I am unable to get the file through Unity Engine, I had to write custom plugin is Java and use that in Unity Project and that some how has worked.
Following is the code which return string after reading the file on both rooted and non rooted devices
public static String getCocos2DPrefsFile(String mPackageName)
{
//Get the text file
File file = new File("/data/data/"+mPackageName+"/shared_prefs/","Cocos2dxPrefsFile.xml");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
Log.d("Error", e.toString());
}
return text.toString();
}

Reading File Assets for Tests in IntelliJ Android Application

I don't think this is an IntelliJ issue specifically but giving all the details regardless. I created an Android Test Application in IntelliJ 13 and I'm trying to test some existing code in an Android application. This bit of code accepts an InputStream which is a JSON file to be read. I am trying to test a method for reading this file InputStream. I have the following:
My project structure looks like this:
android_test
- libs
- res
- src
- testAssetes
- file.json
And my test method is:
public void testParseFile() {
FileInputStream in = new FileInputStream(new File("./testAssets/file.json"));
// code continues..
}
I keep getting a FileNotFound exception. I've also tried the following:
android_test
- libs
- res
- src
- com
- test
- file.json
And then my code is modified to:
InputStream in = getClass().getResourceAsStream("/com/test/file.json")
And in this case, the InputStream is always null. I created a regular java project with similar code and it worked just fine. Not sure if it has something to do with how the InstrumentTestRunner is working or what the deal is.
UPDATE: I just realized that the problem is probably because these tests are running with the InstrumentationTestRunner which executes on the emulator/device. So I think what I need to know is how to get my test file on to that file system and read it in for a test.
You can specify the android_test directory as the "Working directory" in IntelliJ via "Run > Edit Configurations"
One way to do it is to use a bit of reflection. A utility method I use is :
public String assetFileContents(final String fileName) throws IOException {
StringBuilder text = new StringBuilder();
InputStream fileStream = this.getClass().getClassLoader()
.getResourceAsStream("assets/" + fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(fileStream));
String line;
while((line = reader.readLine()) != null) {
text.append(line);
}
return text.toString();
}
This return the String content of fileName. Also, I keep the test files in assets folder at /src/tests/assets (set via assets.srcDir in build.gradle, I think default has instrumentTests instead of tests)
I don't think the InstrumentTestRunner argument is relevant. As long as it's in the source path folders it should be packaged along with the app.
To see running examples using test files, see my repository here (FYI, I'm currently refactoring the project, they might have moved to another branch at a later point).

Faster media scanning algorithm for android

I am working n in the meanwhile learning to code in android
I came across this mediastore which returns all the details about all the mp3 files stored on the card(Internal & External).
But this method is very very slow
I guess that's what has been implemented in the default music application
No wonder it sometimes fails to find out all the files...
I was thinking of implementing a faster search algorithm for this purpose, But am confused with the initial requirements of these algorithms
1: I thought of implementing the Binary search method (Divide n Conquer) to find files, but then the algorithm requires information about the number of files to be scanned.How do I get that?
2: I thought of implementing separate threads for each divided cluster.But then will it really work?
Plz help me in this!
the last question : How in the world does poweramp find out all the files so quickly,
My android has about 200 songs on the card, but this app only takes some seconds to get them all!!
Really puzzled!!
Try this code:
go to Download and DCIM folder there you can use this command to get all files and if you want to filter files then here is the link
Process process = null;
try {
process = Runtime.getRuntime().exec("ls -l");
} catch (IOException ez) {
ez.printStackTrace();
}
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder total = new StringBuilder();
String line;
try {
while ((line = in.readLine()) != null) {
System.out.println("line: "+line.toString());
total.append(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println("Command Output: "+total.toString());

Android - reading a text file from Assets seems to include a LOT of junk before/after the actual data?

I package a text file with my Android App (in Assets) which I read within the App itself.
To avoid this file being compressed, it's named 'mytestfile.mp3' and until recently, that worked just fine.
In one of the recent SDK/ADT changes, it seems something 'odd' is happening when reading from Assets and I'm open to ideas as to what it is...
I use code something like this
AssetFileDescriptor descriptor = getAssets().openFd("mytextfile.mp3");
BufferedReader f = new BufferedReader(new FileReader(descriptor.getFileDescriptor()));
String line = f.readLine();
while (line != null) {
// do stuff
Log.d("TAG",line);
}
What I'm now seeing from the Log is rather odd - if the file contained something like this
Fred
Barney
Wilma
I'm seeing huge amounts of nonsense like this in the log
��ߴ�!�c�W���6�f����m�>ߩ���'�����6�#6���l0��mp�
followed - eventually by my text content
Fred
Barney
Wilma
followed by another metric tonne of gibberish - some of which looks like this
����������4�u?'����������������������������������������res/drawable-mdpi/icon.pngPK��������|v?,������������'�����������������������������res/layout-land/dialog_color_picker.xmlPK��������|v?1�!�����t2�������������������������������classes.dexPK��������|v?թVڝ����5���������������������������������META-INF/MANIFEST.MFPK��������|v?�v������j���������������������������������META-INF/CERT.SFPK��������|v?W7#�]�������������������������������������META-INF/CERT.RSAPK������������������������
As you can see, that appears to be raw binary content from the APK (and nothing to do with the text file)??
Is this a recent packaging issue or am I missing something? I'm using ADT15 but I've not tried the recent upgrade just yet!?
p.s. I've upgraded to the latest SDK/ADT and this problem persists - obviously I'd like to escalate it with whoever is at fault (no idea if the problem is Eclipse/ADT/ANT or Android centered) and so I'll start a bounty for ideas...
This is because AssetFileDescriptor.getFileDescriptor() is for your .apk and not the mytextfile.mp3 file inside the .apk. To work with AssetFileDescriptor you need to take e.g. AssetFileDescriptor.getStartOffset() into account as well, which is the offset to the actual file i.e. mytextfile.mp3 in your case.
But there's an easy solution to your problem. Use AssetManager.open(String) instead, which will give you an InputStream to the mytextfile.mp3 file. Like this:
InputStream inputStream = getAssets().open("mytextfile.mp3");
BufferedReader f = new BufferedReader(new InputStreamReader(inputStream));
// ...
Eclipse/ADT occasionally gets the resources corrupted. Try doing a project clean and rebuild to see if that fixes it.
I had the same problem with my app. Try using Apache Commons IO's FileUtils.
This adds another 100kb to your apk, but make File handling much easier.
And if you store the file as myfile.txt instead of .mp3, does it give the same output?
And did you create the file with a Windows or Linux/Unix System? (And with what application?)
/edit: This works for me:
AssetManager am = this.getAssets();
InputStream is = am.open("mytextfile.mp3");
InputStreamReader inputStreamReader = new InputStreamReader(is);
BufferedReader f = new BufferedReader(inputStreamReader);
String line = f.readLine();
while (line != null) {
// do stuff
Log.d("TAG", line);
line = f.readLine();
}

Categories

Resources