Native Android can also do web development.

Source: Internet
Author: User
Tags html form

Native Android can also do web development.

Copyright NOTICE: Reprint must indicate this article transferred from Zhangjie's blog: http://blog.yanzhenjie.com

Hello everyone, today we introduce an open source project--andserver that allows native Android to do web development as well.

Open Source Address: https://github.com/yanzhenjie/AndServer

AndServeris an Android Web server, similar to Apache or Tomcat, but different, it is a normal Android Library,android Project Gradle remote dependency or add Jar package can be introduced to the project, Then we developed the app just like normal Android.

AndServeris to use the pure Android API to write a library, so no third-party library or any hardware compiled, hit the jar package only 580kb.

Many people see the question here: What is its usage scenario? according to international practice, I raise a chestnut:

A company exposes a TV APP that can be installed on a television or a box, with one function:
When the app is installed on the TV, a unique ID is generated, and the user uses a scan code to bind to the company's public number and the app on the TV, and the user opens a H5 page with a public number that uploads the image or video to the server, and the server detects the user and a screen's app bindings. Dynamically send the user's pictures or videos to the TV broadcast.
Such a feature is a good experience, but the cost of server resources, remote upload, remote download also takes time, as I directly with a USB flash drive to the TV. So if I send a video or a picture directly to the TV app on the LAN via the Web, wouldn't it be more direct and fast?

Of course, most of the students may have little contact with each other in the LAN communication, LAN upload download, LAN login Such demand, there are a lot of chestnuts I will not raise, the following began the official Amway.

Characteristics
    1. Accept client file upload, download file.
    2. The dynamic HTTP API, like the Java servlet, writes the interface.
    3. Deploy static Web sites, such as plain HTML, to support JS, CSS, image separation.
    4. Deploying dynamic Web sites, such as HTML forms, can of course be combined with the Android HTTP interface above.

Basically the same functionality as the Java servlet, if you've done Java development or Web development in other languages should be familiar.

Depend on
    • Gradle
‘com.yanzhenjie:andserver:1.0.2‘
    • Maven
<dependency>  <groupId>com.yanzhenjie</groupId>  <artifactId>andserver</artifactId>  <version>1.0.2</version>  <type>pom</type></dependency>
    • ADT, you can go to the Andserver home page to download the jar package.
How to use

The best tutorial is to sample recommend to the Andserver home page download sample run to see the effect, and then combined with the README is more clear.

Creating a server
new AndServer.Build()    ...    .build();// 创建服务器。Server mServer = andServer.createServer();...// 启动服务器。mServer.start();...// 停止服务器。mServer.stop();...// 服务器正在运行吗?boolean running = mServer.isRunning();
Port number and Response timeout settings
new AndServer.Build()    .port(8080// 默认是8080,Android平台允许的端口号都可以。    .timeout(101000// 默认10 * 1000毫秒。    ...    .build();...
Deploying Web Sites

Deploying a Web site is through an Website interface, and you can implement this interface yourself, which of course AndServer already provides two default implementations:

    • Assetswebsite
    • Storagewebsite

If you use the above two implementations to register your site, then your default home page ( index.html ) is:

http://ip:port/http://ip:port/youPathhttp://ip:port/youPath/index.html
Register website to Andserver
new AssetsWebsite(AssetManager, youPath);// 或者newnew AndServer.Build()    ...    .website(wesite);    .build();
Use of Assetswebsite

If your site is assets under, then you use it AssetsWebsite to deploy your site.

Use this method:

//AssetManager不能被关闭。new AssetsWebsite(mAssetManager, youPath);

Above we see the new assetswebsite need to pass a assetmanager and a Path,path support assets root directory and subdirectories, the following are examples of these two cases.

    • If your site is in the assets root directory, you path fill it out "" , for example:

new"");

Then your default homepage access address is:

http://ip:porthttp://ip:port/index.html

Then your other page access address is:

http://ip:port/login.htmlhttp://ip:port/error.html

Like what:

http://192.168.1.12:8080/index.html  http://192.168.1.12:8080/login.html
    • If your site root directory in assets the subdirectory, then you passed assets the relative directory address is good, such as your site in the assets next web directory, for example:

new"web");

Then your default homepage access address is:

http://ip:porthttp://ip:port/webhttp://ip:port/web/index.html

Then your other page access address is:

http://ip:port/web/login.htmlhttp://ip:port/web/error.html

For example:

http://192.168. 1.:8080/http://192.168. 1.:8080/index. htmlhttp://192.168. 1.:8080/web/index. htmlhttp://192.168. 1.:8080/web/index. html  http://192.168. 1.:8080/web/login. html
Use of Storagewebsite

If your site is under a memory device and can be read as a file, then you use it StorageWebsite to deploy your website, such as when your site is under the SD card.

Use this method:

new StorageWebsite(youPath);

It's simple, just pass in your site's storage directory address, such as your site under the SD card www directory:

new"www"new StorageWebsite(websiteDirectory);

The access address AssetsWebsite is the same as the reason.

Write an HTTP interface like a servlet

The Http API is RequestHandler registered through an interface, which is the java interface same as it Java is Servlet .

You need to implement this interface and then AndServer register it, for example:

 Public  class Requestloginhandler implements RequestHandler {    @Override     Public void Handle(HttpRequest req, HttpResponse Res, HttpContext con) {map<string, string> params = httprequestparser.parse (request);//Request params. String userName = Params.get ("username"); String Password = params.get ("Password");if("123". Equals (UserName) &&"123". Equals (password)) {stringentity stringentity =NewStringentity ("Login succeed","Utf-8");        Response.setentity (stringentity); }Else{Stringentity stringentity =NewStringentity ("Login Failed","Utf-8");        Response.setentity (stringentity); }    }}

Then AndServer register in:

new AndServer.Build()    ...    .registerHandler("login"new RequestLoginHandler())    .build();

Now you get a unique access address: http://ip:port/login For example:

http://192.168.1.12:8080/login?username=123&password=123

File download and file upload examples please download to sample view.

Submit an HTML form to the Android side

In the of the Html form fill in action your registration RequestHandler when you key can, and then in RequestHandler the

handle(HttpRequest, HttpResponse, HttpContext)

method to get form the arguments for the submission.

For example, we registered Login RequestHandler in the above to form use:

<form id="form1" method="post" action="login">...</form>
Monitor the status of the server

The server generally has three states: successful start, failure at startup, successful stopping of the server, an exception is returned when the failure occurs, usually a network problem or a port is occupied.

PrivateServer.listener Mlistener =NewServer.listener () {@Override     Public void onstarted() {//server started successfully.}@Override     Public void onstopped() {//The server stopped, usually the developer calls Server.stop () to stop. }@Override     Public void OnError(Exception e) {//server startup error, usually port is occupied. }}; Andserver Andserver =NewAndserver.build () .... Listener (Mlistener). build ();

If you think it's good, please follow my public number.

Copyright NOTICE: Reprint must indicate this article transferred from Zhangjie's blog: http://blog.yanzhenjie.com

Native Android can also do web development.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.