This article has been published on my public account hongyangAndroid.

An overview of the

Today, when I was browsing Jane’s books, I found a library:

  • www.jianshu.com/p/e0c172c4e…
  • Github.com/MZCretin/Wi…

The main function is as follows: first, when opening the APP, you can access an address through the browser, and then upload apK to the mobile phone through the browser (it also supports deleting the existing APK), and then the mobile phone can install and uninstall the APK.

Just three pictures:

After the application starts:

Then PC side access:

Drag and drop apK upload to upload to mobile phone.

Ok, that’s pretty clear.

Be sure to be on the same network segment.

Let’s not talk about how useful it is, a lot of times when I see a project, I rarely consider what it can do, what I consider most is how it is implemented, can I learn, not that, as for what can be done, that is after I learn?

So if you think about his implementation, this way of uploading files, which is more common on the PC side, uploading files to the server.

Speaking of which, it can be thought that maybe the app builds a server on the phone.

Yes, that’s right. A server is built on the mobile phone, so that you can pass HTML to the PC file to the mobile phone, and then the mobile phone receives it and then synchronizes the interface.

At the same time, you can also present the files on the Sdcard on the mobile phone completely on the PC.

The Server on the mobile side makes use of this library:

  • https://github.com/koush/AndroidAsync

Parsing the source code of things do not do, are interested in their own learning, then began the main film.

A group friend problem

I came to the attention of this library because a guy in the WanAndroid group has been asking a question for a long time. The question is:

  • How do I enter an address in the browser to play video on my phone

At that time, many people answered that the core of the answer was correct.

Of course, I happened to see this library and had never posted anything about it before, so I decided to write a simple Demo.

Of course, Demo is not what beautiful at all, only for the rapid implementation of the effect.

The renderings look like this:

The page displays a list of videos on the phone, and then clicks on a video to start playing the video.

With the above example in mind, it’s very simple.

Note: Some code copy directly from the above example. This case requires network and Sdcard permissions!

Let’s get the server up

Dependent libraries

First of all, depending on the library we need to build the Server:

compile 'com.koushikdutta.async:androidasync:2.+'
Copy the code

Write simple HTML

Then we write an HTML file under Assets for the browser to access, index.html

The simplest is:

<! DOCTYPE HTML > < HTML > <head> <meta charset=" utF-8 "> </head> <body> </body> </html>Copy the code

Start the service and listen on the port

public class MainActivity extends AppCompatActivity { private AsyncHttpServer server = new AsyncHttpServer(); private AsyncServer mAsyncServer = new AsyncServer(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); server.get("/", new HttpServerRequestCallback() { @Override public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) { try { response.send(getIndexContent()); } catch (IOException e) { e.printStackTrace(); response.code(500).end(); }}}); server.listen(mAsyncServer, 54321); } @Override protected void onDestroy() { super.onDestroy(); if (server ! = null) { server.stop(); } if (mAsyncServer ! = null) { mAsyncServer.stop(); } } private String getIndexContent() throws IOException { BufferedInputStream bInputStream = null; try { bInputStream = new BufferedInputStream(getAssets().open("index.html")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len = 0; byte[] tmp = new byte[10240]; while ((len = bInputStream.read(tmp)) > 0) { baos.write(tmp, 0, len); } return new String(baos.toByteArray(), "utf-8"); } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (bInputStream ! = null) { try { bInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }Copy the code

As you can see, it’s very simple. To create AsyncHttpServer, we call get in onCreate and set up a GET URL listener that listens to /, the root directory.

Then call LISTEN, passing in port number 54321, to enable listening on that port.

Stop the server when onDestroy is done.

When an access to “/” is captured, the index.html under assets is read and returned to the browser.

Remember to add network permissions.

All right, run demo, test it out.

Enter the address, your phone’s IP: port number.

Note that your computer is on the same network segment as your phone!

Then you should see the following effect:

If you don’t see it, don’t go down

Perfect the Demo

Next, we return the MP4 on the phone to display in the browser.

Very simple, since we can listen for/to return an index.html, we can listen for another URL to return the file directory.

server.get("/files", new HttpServerRequestCallback() { @Override public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) { JSONArray array = new JSONArray(); File dir = new File(Environment.getExternalStorageDirectory().getPath()); String[] fileNames = dir.list(); if (fileNames ! = null) { for (String fileName : fileNames) { File file = new File(dir, fileName); if (file.exists() && file.isFile() && file.getName().endsWith(".mp4")) { try { JSONObject jsonObject = new JSONObject();  jsonObject.put("name", fileName); jsonObject.put("path", file.getAbsolutePath()); array.put(jsonObject); } catch (JSONException e) { e.printStackTrace(); } } } } response.send(array.toString()); }});Copy the code

We listen for the Url /files and return the video file from Sdcard root, splicing it together as JSON.

Here if you reboot, type in your browser:

http://192.168.1.100:54321/files
Copy the code

You’ll see a bunch of JSON data:

But we need to display it on the previous HTML, so the request should be made on the previous HTML page:

<! DOCTYPE HTML >< HTML >< head> <meta charset="UTF-8"> <script SRC ="jquery-1.7.2.min.js" type="text/javascript"></script> $(function() {var now = new Date(); var url = 'files' + '? ' + now.getTime(); $.getjson (url, function(data) {// Edit JSON array for (var I = 0; i < data.length; I++) {/ / for each object generates an li tag, added to the page of ul var $li = $(' < li > '+ data [I] name +' < / li > '); $li.attr("path", data[i].path); $("#filelist").append($li); }}); }); </script> </head> <body> <ul id="filelist" style="float:left;" ></ul> </body> </html>Copy the code

$.getjson retrieves the returned JSON array and iterates to generate a LI tag for each JSON object to add to the page.

Here using jquery, for JS also need also request processing, here omitted, very simple, see the source code.

At this point, you can already display the video directory:

The next step is to hit Play. In the HTML, there is a tag called video that plays the video, and it has a SRC attribute that sets the path of the video to play.

So all we need to do is:

  • Click the name to get the corresponding URL of the video, and then set the SRC attribute for the video.

So what’s the URL of the video?

We just returned the path of the video, so we’re just listening for another URL, and we’re going to stream the video file back based on the path of the video that was passed in.

server.get("/files/.*", new HttpServerRequestCallback() {
    @Override
    public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        String path = request.getPath().replace("/files/", "");
        try {
            path = URLDecoder.decode(path, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        File file = new File(path);
        if (file.exists() && file.isFile()) {
            try {
                FileInputStream fis = new FileInputStream(file);
                response.sendStream(fis, fis.available());
            } catch (Exception e) {
                e.printStackTrace();
            } 
            return;
        }
        response.code(404).send("Not found!");
    }
});
Copy the code

We listened to another URL as files/ XXX.*, after capturing it, we got the file name, went to SDCard to find the file, and returned the file stream.

The code on the HTML side is:

<script type="text/javascript"> $(function() { var now = new Date(); Var $video = $("# videoPlayer "); var url = 'files' + '? ' + now.getTime(); $.getJSON(url, function(data) { for (var i = 0; i < data.length; i++) { var $li = $('<li>' + data[i].name + '</li>'); $li.attr("path", data[i].path); $("#filelist").append($li); $li.click(function() {var p = "/files/" + $(this).attr("path"); $video.attr("src", "/files/" + $(this).attr("path")); $video[0].play(); }); }}); }); </script>Copy the code

Of course, there is a video tag inside the body tag on the page.

 <video id="videoplayer" controls="controls">
 </video>
Copy the code

Here, so the code is introduced ~~

summary

Looking back, the app starts the server, listens for some urls, and returns text, JSON, file streams, etc.

Of course, you can do a lot of things, even a PC version of the file browser.

There may be a lot of people are not familiar with HTML, JS, but I still recommend a simple understanding, or click on this example, because this example code is very little, it is worth getting started as a tutorial.

Source code address:

Github.com/hongyangAnd…