Thursday, August 21, 2014

PhoneGap 3.x Mobile Application Development Hotshot

Create useful and exciting real-world apps for iOS and Android devices with 12 fantastic projects with this book and ebook.

PhoneGap 3.x Mobile Application Development Hotshot

Overview
  • Use PhoneGap 3.x effectively to build real, functional mobile apps ranging from productivity apps to a simple arcade game
  • Explore often-used design patterns in apps designed for mobile devices
  • Fully practical, project-based approach to give you the confidence in developing your app independently
In Detail

PhoneGap allows you to use your existing knowledge of HTML, CSS, and JavaScript to create useful and exciting mobile applications.

This book will present you with 12 exciting projects that will introduce you to the dynamic world of app development in PhoneGap. Starting with their design and following through to their completion, you will develop real-world mobile applications. Each app uses a combination of core PhoneGap technologies, plugins, and various frameworks covering the necessary concepts you can use to create many more great apps for mobile devices.

What you will learn from this book
  • Explore localization and globalization
  • Create, save, and retrieve data using persistent device storage
  • Record audio using a microphone
  • Capture images and video using a camera
  • Share content to social media networks
  • Optimize your app for tablet-sized devices
  • Locate the user's device using geolocation
  • Interact with the accelerometer to create a fun arcade game
  • Use core and third-party plugins to extend PhoneGap
  • Look at mobile application design patterns
Approach

A practical guide written in a tutorial-style, this book walks you step-by-step through 12 individual projects to create real world apps. Each project moves through design and implementation of the app, and also provides suggestions to enhance it.

Who this book is written for

If you are a mobile developer who is familiar with Phonegap basics and wants to quickly create some cool mobile applications with Phonegap, this book is for you. You should have some experience working with JavaScript, HTML, CSS, and also be able to use your operating system's command-line interface. No experience with Java, C#, or Objective C is required.



Tuesday, August 19, 2014

Java Chat Server running on PC command line

The former post show how to "Implement simple Android Chat Application, server side" running on Android. Actually, it show info of IP/Port only, without any user interaction. This post is another command line version of the Chat Server in Java, it can run on PC's ommand Line. It can connected with "Simple Android Chat Application, client side".

The video show it was compiled with SDK 8, and run on command line, at PC running Ubuntu Linux.


JavaCmdChatServer.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class JavaCmdChatServer {

    static final int SocketServerPORT = 8080;

    String msgLog = "";

    List<ChatClient> userList;

    ServerSocket serverSocket;

    public static void main(String[] args) {
        JavaCmdChatServer ChatServer = new JavaCmdChatServer();

        while (true) {
        }
    }

    JavaCmdChatServer() {
        System.out.print(getIpAddress());
        userList = new ArrayList<>();
        ChatServerThread chatServerThread = new ChatServerThread();
        chatServerThread.start();

    }

    private class ChatServerThread extends Thread {

        @Override
        public void run() {
            Socket socket = null;

            try {
                serverSocket = new ServerSocket(SocketServerPORT);
                System.out.println("I'm waiting here: "
                    + serverSocket.getLocalPort());
                    System.out.println("CTRL + C to quit");

                while (true) {
                    socket = serverSocket.accept();
                    ChatClient client = new ChatClient();
                    userList.add(client);
                    ConnectThread connectThread = new ConnectThread(client, socket);
                    connectThread.start();
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

        }

    }

    private class ConnectThread extends Thread {

        Socket socket;
        ChatClient connectClient;
        String msgToSend = "";

        ConnectThread(ChatClient client, Socket socket) {
            connectClient = client;
            this.socket = socket;
            client.socket = socket;
            client.chatThread = this;
        }

        @Override
        public void run() {
            DataInputStream dataInputStream = null;
            DataOutputStream dataOutputStream = null;

            try {
                dataInputStream = new DataInputStream(socket.getInputStream());
                dataOutputStream = new DataOutputStream(socket.getOutputStream());

                String n = dataInputStream.readUTF();

                connectClient.name = n;

                msgLog = connectClient.name + " connected@"
                    + connectClient.socket.getInetAddress()
                    + ":" + connectClient.socket.getPort() + "\n";

                System.out.println(msgLog);

                dataOutputStream.writeUTF("Welcome " + n + "\n");
                dataOutputStream.flush();

                broadcastMsg(n + " join our chat.\n");

                while (true) {
                    if (dataInputStream.available() > 0) {
                        String newMsg = dataInputStream.readUTF();

                        msgLog = n + ": " + newMsg;
                        System.out.print(msgLog);
                        broadcastMsg(n + ": " + newMsg);
                    }

                    if (!msgToSend.equals("")) {
                        dataOutputStream.writeUTF(msgToSend);
                        dataOutputStream.flush();
                        msgToSend = "";
                    }

                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (dataInputStream != null) {
                    try {
                        dataInputStream.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                if (dataOutputStream != null) {
                    try {
                        dataOutputStream.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                userList.remove(connectClient);

                System.out.println(connectClient.name + " removed.");

                msgLog = "-- " + connectClient.name + " leaved\n";
                System.out.println(msgLog);

                broadcastMsg("-- " + connectClient.name + " leaved\n");

            }

        }

        private void sendMsg(String msg) {
            msgToSend = msg;
        }

    }

    private void broadcastMsg(String msg) {
        for (int i = 0; i < userList.size(); i++) {
            userList.get(i).chatThread.sendMsg(msg);
            msgLog = "- send to " + userList.get(i).name + "\n";
            System.out.print(msgLog);
        }
        System.out.println();
        
    }

    private String getIpAddress() {
        String ip = "";
        try {
            Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                .getNetworkInterfaces();
            while (enumNetworkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = enumNetworkInterfaces
                    .nextElement();
                Enumeration<InetAddress> enumInetAddress = networkInterface
                    .getInetAddresses();
                while (enumInetAddress.hasMoreElements()) {
                    InetAddress inetAddress = enumInetAddress.nextElement();

                    if (inetAddress.isSiteLocalAddress()) {
                        ip += "SiteLocalAddress: "
                            + inetAddress.getHostAddress() + "\n";
                    }

                }

            }

        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            ip += "Something Wrong! " + e.toString() + "\n";
        }

        return ip;
    }

    class ChatClient {

        String name;
        Socket socket;
        ConnectThread chatThread;

    }

}

download filesDownload the files.

Monday, August 18, 2014

Simple Android Chat Application, client side.

It's client side of Simple Android Chat Application, for the server side, refer last post "Implement simple Android Chat Application, server side".


MainActivity.java
package com.example.androidchatclient;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
 
 static final int SocketServerPORT = 8080;
 
 LinearLayout loginPanel, chatPanel;

 EditText editTextUserName, editTextAddress;
 Button buttonConnect;
 TextView chatMsg, textPort;
 
 EditText editTextSay;
 Button buttonSend;
 Button buttonDisconnect;

 String msgLog = "";
 
 ChatClientThread chatClientThread = null;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  loginPanel = (LinearLayout)findViewById(R.id.loginpanel);
  chatPanel = (LinearLayout)findViewById(R.id.chatpanel);

  editTextUserName = (EditText) findViewById(R.id.username);
  editTextAddress = (EditText) findViewById(R.id.address);
  textPort = (TextView) findViewById(R.id.port);
  textPort.setText("port: " + SocketServerPORT);
  buttonConnect = (Button) findViewById(R.id.connect);
  buttonDisconnect = (Button) findViewById(R.id.disconnect);
  chatMsg = (TextView) findViewById(R.id.chatmsg);

  buttonConnect.setOnClickListener(buttonConnectOnClickListener);
  buttonDisconnect.setOnClickListener(buttonDisconnectOnClickListener);
  
  editTextSay = (EditText)findViewById(R.id.say);
  buttonSend = (Button)findViewById(R.id.send);
  
  buttonSend.setOnClickListener(buttonSendOnClickListener);
 }
 
 OnClickListener buttonDisconnectOnClickListener = new OnClickListener() {

  @Override
  public void onClick(View v) {
   if(chatClientThread==null){
    return;
   }
   chatClientThread.disconnect();
  }
  
 };
 
 OnClickListener buttonSendOnClickListener = new OnClickListener() {

  @Override
  public void onClick(View v) {
   if (editTextSay.getText().toString().equals("")) {
    return;
   }
   
   if(chatClientThread==null){
    return;
   }
   
   chatClientThread.sendMsg(editTextSay.getText().toString() + "\n");
  }
  
 };

 OnClickListener buttonConnectOnClickListener = new OnClickListener() {

  @Override
  public void onClick(View v) {
   String textUserName = editTextUserName.getText().toString();
   if (textUserName.equals("")) {
    Toast.makeText(MainActivity.this, "Enter User Name",
      Toast.LENGTH_LONG).show();
    return;
   }

   String textAddress = editTextAddress.getText().toString();
   if (textAddress.equals("")) {
    Toast.makeText(MainActivity.this, "Enter Addresse",
      Toast.LENGTH_LONG).show();
    return;
   }
   
   msgLog = "";
   chatMsg.setText(msgLog);
   loginPanel.setVisibility(View.GONE);
   chatPanel.setVisibility(View.VISIBLE);

   chatClientThread = new ChatClientThread(
     textUserName, textAddress, SocketServerPORT);
   chatClientThread.start();
  }

 };

 private class ChatClientThread extends Thread {

  String name;
  String dstAddress;
  int dstPort;
  
  String msgToSend = "";
  boolean goOut = false;

  ChatClientThread(String name, String address, int port) {
   this.name = name;
   dstAddress = address;
   dstPort = port;
  }

  @Override
  public void run() {
   Socket socket = null;
   DataOutputStream dataOutputStream = null;
   DataInputStream dataInputStream = null;

   try {
    socket = new Socket(dstAddress, dstPort);
    dataOutputStream = new DataOutputStream(
      socket.getOutputStream());
    dataInputStream = new DataInputStream(socket.getInputStream());
    dataOutputStream.writeUTF(name);
    dataOutputStream.flush();

    while (!goOut) {
     if (dataInputStream.available() > 0) {
      msgLog += dataInputStream.readUTF();

      MainActivity.this.runOnUiThread(new Runnable() {

       @Override
       public void run() {
        chatMsg.setText(msgLog);
       }
      });
     }
     
     if(!msgToSend.equals("")){
      dataOutputStream.writeUTF(msgToSend);
      dataOutputStream.flush();
      msgToSend = "";
     }
    }

   } catch (UnknownHostException e) {
    e.printStackTrace();
    final String eString = e.toString();
    MainActivity.this.runOnUiThread(new Runnable() {

     @Override
     public void run() {
      Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
     }
     
    });
   } catch (IOException e) {
    e.printStackTrace();
    final String eString = e.toString();
    MainActivity.this.runOnUiThread(new Runnable() {

     @Override
     public void run() {
      Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
     }
     
    });
   } finally {
    if (socket != null) {
     try {
      socket.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }

    if (dataOutputStream != null) {
     try {
      dataOutputStream.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }

    if (dataInputStream != null) {
     try {
      dataInputStream.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }

    MainActivity.this.runOnUiThread(new Runnable() {

     @Override
     public void run() {
      loginPanel.setVisibility(View.VISIBLE);
      chatPanel.setVisibility(View.GONE);
     }
     
    });
   }

  }
  
  private void sendMsg(String msg){
   msgToSend = msg;
  }
  
  private void disconnect(){
   goOut = true;
  }
 }

}

/res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Char Client"
        android:textStyle="bold" />

    <LinearLayout
        android:id="@+id/loginpanel"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="visible" >

        <EditText
            android:id="@+id/username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="User name" />

        <EditText
            android:id="@+id/address"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="dstAddress" />

        <TextView
            android:id="@+id/port"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/connect"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Connect..." />
    </LinearLayout>

 <LinearLayout
        android:id="@+id/chatpanel"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="gone" >
        
        <EditText
            android:id="@+id/say"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Say something" />
     
        <Button
            android:id="@+id/send"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Send" />
        
        <Button
            android:id="@+id/disconnect"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Disconnect" />

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:id="@+id/chatmsg"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </ScrollView>
    </LinearLayout>

</LinearLayout>

Permission of "android.permission.INTERNET" is needed in AndroidManifest.xml.

download filesDownload the files.

Implement simple Android Chat Application, server side.

It's a simple example of Chat app running on Android devices, both server and clients. One device run AndroidChatServer to wait connection from clients, other devices run AndroidChatClient to connect to the server. Any AndroidChatClient can send message to server, then server broadcast to all clients.


Here is the code in Server side, Client side can be found in next post, "Simple Android Chat Application, client side"
.
MainActivity.java
package com.example.androidchatserver;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {

 static final int SocketServerPORT = 8080;

 TextView infoIp, infoPort, chatMsg;

 String msgLog = "";
 
 List<ChatClient> userList;

 ServerSocket serverSocket;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  infoIp = (TextView) findViewById(R.id.infoip);
  infoPort = (TextView) findViewById(R.id.infoport);
  chatMsg = (TextView) findViewById(R.id.chatmsg);

  infoIp.setText(getIpAddress());

  userList = new ArrayList<ChatClient>();
  
  ChatServerThread chatServerThread = new ChatServerThread();
  chatServerThread.start();
 }

 @Override
 protected void onDestroy() {
  super.onDestroy();

  if (serverSocket != null) {
   try {
    serverSocket.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }

 private class ChatServerThread extends Thread {

  @Override
  public void run() {
   Socket socket = null;

   try {
    serverSocket = new ServerSocket(SocketServerPORT);
    MainActivity.this.runOnUiThread(new Runnable() {

     @Override
     public void run() {
      infoPort.setText("I'm waiting here: "
        + serverSocket.getLocalPort());
     }
    });
    
    while (true) {
     socket = serverSocket.accept();
     ChatClient client = new ChatClient();
     userList.add(client);
     ConnectThread connectThread = new ConnectThread(client, socket);
     connectThread.start();
    }

   } catch (IOException e) {
    e.printStackTrace();
   } finally {
    if (socket != null) {
     try {
      socket.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
   }

  }

 }
 
 private class ConnectThread extends Thread {
  
  Socket socket;
  ChatClient connectClient;
  String msgToSend = "";

  ConnectThread(ChatClient client, Socket socket){
   connectClient = client;
   this.socket= socket;
   client.socket = socket;
   client.chatThread = this;
  }

  @Override
  public void run() {
   DataInputStream dataInputStream = null;
   DataOutputStream dataOutputStream = null;
   
   try {
    dataInputStream = new DataInputStream(socket.getInputStream());
    dataOutputStream = new DataOutputStream(socket.getOutputStream());
    
    String n = dataInputStream.readUTF();
    
    connectClient.name = n;
    
    msgLog += connectClient.name + " connected@" + 
      connectClient.socket.getInetAddress() + 
      ":" + connectClient.socket.getPort() + "\n";
    MainActivity.this.runOnUiThread(new Runnable() {

     @Override
     public void run() {
      chatMsg.setText(msgLog);
     }
    });
    
    dataOutputStream.writeUTF("Welcome " + n + "\n");
    dataOutputStream.flush();
    
    broadcastMsg(n + " join our chat.\n");
    
    while (true) {
     if (dataInputStream.available() > 0) {
      String newMsg = dataInputStream.readUTF();
      
      
      msgLog += n + ": " + newMsg;
      MainActivity.this.runOnUiThread(new Runnable() {

       @Override
       public void run() {
        chatMsg.setText(msgLog);
       }
      });
      
      broadcastMsg(n + ": " + newMsg);
     }
     
     if(!msgToSend.equals("")){
      dataOutputStream.writeUTF(msgToSend);
      dataOutputStream.flush();
      msgToSend = "";
     }
     
    }
    
   } catch (IOException e) {
    e.printStackTrace();
   } finally {
    if (dataInputStream != null) {
     try {
      dataInputStream.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }

    if (dataOutputStream != null) {
     try {
      dataOutputStream.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    
    userList.remove(connectClient);
    MainActivity.this.runOnUiThread(new Runnable() {

     @Override
     public void run() {
      Toast.makeText(MainActivity.this, 
       connectClient.name + " removed.", Toast.LENGTH_LONG).show();
      
      msgLog += "-- " + connectClient.name + " leaved\n";
      MainActivity.this.runOnUiThread(new Runnable() {

       @Override
       public void run() {
        chatMsg.setText(msgLog);
       }
      });
      
      broadcastMsg("-- " + connectClient.name + " leaved\n");
     }
    });
   }
   
  }
  
  private void sendMsg(String msg){
   msgToSend = msg;
  }
  
 }
 
 private void broadcastMsg(String msg){
  for(int i=0; i<userList.size(); i++){
   userList.get(i).chatThread.sendMsg(msg);
   msgLog += "- send to " + userList.get(i).name + "\n";
  }
  
  MainActivity.this.runOnUiThread(new Runnable() {

   @Override
   public void run() {
    chatMsg.setText(msgLog);
   }
  });
 }

 private String getIpAddress() {
  String ip = "";
  try {
   Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
     .getNetworkInterfaces();
   while (enumNetworkInterfaces.hasMoreElements()) {
    NetworkInterface networkInterface = enumNetworkInterfaces
      .nextElement();
    Enumeration<InetAddress> enumInetAddress = networkInterface
      .getInetAddresses();
    while (enumInetAddress.hasMoreElements()) {
     InetAddress inetAddress = enumInetAddress.nextElement();

     if (inetAddress.isSiteLocalAddress()) {
      ip += "SiteLocalAddress: "
        + inetAddress.getHostAddress() + "\n";
     }

    }

   }

  } catch (SocketException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   ip += "Something Wrong! " + e.toString() + "\n";
  }

  return ip;
 }

 class ChatClient {
  String name;
  Socket socket;
  ConnectThread chatThread;
  
 }

}

/res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Char Server"
        android:textStyle="bold" />
    
    <TextView
        android:id="@+id/infoport"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="italic" />

    <TextView
        android:id="@+id/infoip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="italic" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <TextView
            android:id="@+id/chatmsg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </ScrollView>

</LinearLayout>

Permission of "android.permission.INTERNET" is needed in AndroidManifest.xml.

download filesDownload the files.

Related:
- Command line version Chat Server.

Saturday, August 16, 2014

Implement simple HTTP server running on Android

Example to implement simple HTTP server on Android:


MainActivity.java
package com.example.androidhttpserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;

import android.support.v7.app.ActionBarActivity;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {

 EditText welcomeMsg;
 TextView infoIp;
 TextView infoMsg;
 String msgLog = "";
 
 ServerSocket httpServerSocket;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  welcomeMsg = (EditText) findViewById(R.id.welcomemsg);
  infoIp = (TextView) findViewById(R.id.infoip);
  infoMsg = (TextView) findViewById(R.id.msg);

  infoIp.setText(getIpAddress() + ":" 
   + HttpServerThread.HttpServerPORT + "\n");

  HttpServerThread httpServerThread = new HttpServerThread();
  httpServerThread.start();
 }
 
 @Override
 protected void onDestroy() {
  super.onDestroy();

  if (httpServerSocket != null) {
   try {
    httpServerSocket.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

 private String getIpAddress() {
  String ip = "";
  try {
   Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
     .getNetworkInterfaces();
   while (enumNetworkInterfaces.hasMoreElements()) {
    NetworkInterface networkInterface = enumNetworkInterfaces
      .nextElement();
    Enumeration<InetAddress> enumInetAddress = networkInterface
      .getInetAddresses();
    while (enumInetAddress.hasMoreElements()) {
     InetAddress inetAddress = enumInetAddress.nextElement();

     if (inetAddress.isSiteLocalAddress()) {
      ip += "SiteLocalAddress: "
        + inetAddress.getHostAddress() + "\n";
     }

    }

   }

  } catch (SocketException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   ip += "Something Wrong! " + e.toString() + "\n";
  }

  return ip;
 }
 
 private class HttpServerThread extends Thread {
  
  static final int HttpServerPORT = 8888;

  @Override
  public void run() {
   Socket socket = null;
   
   try {
    httpServerSocket = new ServerSocket(HttpServerPORT);
    
    while(true){
     socket = httpServerSocket.accept();

     HttpResponseThread httpResponseThread = 
      new HttpResponseThread(
       socket, 
       welcomeMsg.getText().toString());
     httpResponseThread.start();
    }
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

  }

  
 }
 
 private class HttpResponseThread extends Thread {
  
  Socket socket;
  String h1;
  
  HttpResponseThread(Socket socket, String msg){
   this.socket = socket;
   h1 = msg;
  }

  @Override
  public void run() {
   BufferedReader is;
   PrintWriter os;
   String request;
   
   
   try {
    is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    request = is.readLine();
    
    os = new PrintWriter(socket.getOutputStream(), true);
    
    String response = 
     "<html><head></head>" +
     "<body>" +
     "<h1>" + h1 + "</h1>" +
     "</body></html>";
    
    os.print("HTTP/1.0 200" + "\r\n");
    os.print("Content type: text/html" + "\r\n");
    os.print("Content length: " + response.length() + "\r\n");
    os.print("\r\n");
    os.print(response + "\r\n");
    os.flush();
    socket.close();
    
    
    msgLog += "Request of " + request 
      + " from " + socket.getInetAddress().toString() + "\n";
    MainActivity.this.runOnUiThread(new Runnable() {

     @Override
     public void run() {
      
      infoMsg.setText(msgLog);
     }
    });
    
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   
   return;
  }
 }

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />
    
    <EditText
        android:id="@+id/welcomemsg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Welcome from Android-er" />

    <TextView
        android:id="@+id/infoip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <TextView
            android:id="@+id/msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </ScrollView>

</LinearLayout>


download filesDownload the files.