0% found this document useful (0 votes)
35 views10 pages

Hello Threads

This document describes how to create an Android application with a background thread that acts as a UDP server. The main activity creates and starts the server thread. The server thread opens a socket, receives UDP packets, and sends messages to the main activity using a handler. The main activity updates the UI by handling messages from the server thread. The server thread runs continuously in a loop as long as the socket is open, receiving packets and sending messages to the handler.

Uploaded by

2saeful5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views10 pages

Hello Threads

This document describes how to create an Android application with a background thread that acts as a UDP server. The main activity creates and starts the server thread. The server thread opens a socket, receives UDP packets, and sends messages to the main activity using a handler. The main activity updates the UI by handling messages from the server thread. The server thread runs continuously in a loop as long as the socket is open, receiving packets and sending messages to the handler.

Uploaded by

2saeful5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 10

Android

Introduction
Hello Threads

@2010 Mihail L. Sichitiu

Goal

Create an application
that uses a
background thread
as a UDP server to
receive messages
from the UDP client

@2010 Mihail L. Sichitiu

152.4.244.125

Text sent from UDPClient

Layout
TextView that changes
from Starting Server to
Server Started (optional)
152.4.244.125

TextView that shows the


IP address of the server
(needed for UDPClient)

Text sent from UDPClient

Clear Button clears the


Last Message (and shows
that interface is still
responsive)

TextView that shows the


text sent from UDPClient

@2010 Mihail L. Sichitiu

Application Structure
ServerThread

Main Activity
OnCreate( )

Constructor

Create the thread


Start the thread

UDPClient

Read line from input

Open the Socket


If successful Server Started
Find and display the IP Address

run( )

Message
Handler

while (socketStillOpen){
receive packet
display Message
send reply
}

OnDestroy( )

Send line to Server

Receive line from Server

close the socket

OnClickListener( )

Display line

Clear the Last Message

HelloThreads

@2010 Mihail L. Sichitiu

UDPClient

Main Activity
(HelloThreads)

ClassMembers

TextView
isRunning,myIPAddressField,lastMessage;
Button
clear;
ServerThread myThread;
Handler

OnCreate( )

Get handles (findViewById) to all GUI elements


Create ServerThread: myThread=new
ServerThread(getApplicationContext(),mHandler)
Start the Thread: myThread.start();
Register the OnClickListener for the Clear Button

OnDestroy( )

Handler
Definition on
Next page

myThread.closeSocket();

OnClickListener( )

Clear the Last Message

@2010 Mihail L. Sichitiu

The Handler Definition

private final Handler mHandler = new Handler() {


public void handleMessage(Message msg) {

switch (msg.what) {

case PACKET_CAME:

String incomingMessage = (String) msg.obj;

lastMessage.setText(incomingMessage);

break;

case IS_RUNNING:

String socketStatus = (String) msg.obj;

isRunning.setText(socketStatus);

break;

case IP_ADDRESS:

InetAddress myIPAddress = (InetAddress) msg.obj;

myIPAddressField.setText("Server IP Address:"+myIPAddress.toString());

break;

}
}
};

@2010 Mihail L. Sichitiu

ServerThread

public class ServerThread extends Thread


Class Members

public ServerThread(Context currentContext,Handler handler){

mContext = currentContext;
mHandler = handler;
Open the socket; if successful
mHandler.obtainMessage(HelloThreads2.IS_RUNNING, "Server
On Next
Started").sendToTarget();
Page
InetAddress myIP = getMyWiFiIPAddress();
mHandler.obtainMessage(HelloThreads2.IP_ADDRESS, myIP).sendToTarget();

public void closeSocket()

Handler mHandler; // link to the Message Handler


Context mContext; // link to application context
DatagramSocket serverSocket; // the UDP socket well receive at

serverSocket.close();

public void run()

On Next
Next Page
@2010 Mihail L. Sichitiu

Allows the socket to


be closed (call from
OnDestroy())
7

Getting the IP Address:


getMyWiFiIPAddress( );
WifiManager mWifi = (WifiManager)
(mContext.getSystemService(Context.WIFI_SERVICE));
WifiInfo info = mWifi.getConnectionInfo();
DhcpInfo dhcp = mWifi.getDhcpInfo();
int myIntegerIPAddress = dhcp.ipAddress;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((myIntegerIPAddress>> k * 8) & 0xFF);
try{
InetAddress myIPAddress = InetAddress.getByAddress(quads);
return myIPAddress;
}catch(Exception e){
if(D) Log.e(TAG,"Cannot Get My Own IP Address");
return null
}

@2010 Mihail L. Sichitiu

ServerThread.run( )

boolean socketOK=true; // True as long as we don't get


socket errors
Handles multiple requests
as long as the socket is OK
while(socketOK) {

DatagramPacket receivePacket = new DatagramPacket(receiveData,


receiveData.length);
try{
Blocks
serverSocket.receive(receivePacket);
/*** ..... Same as the UDP server ........ ****/
mHandler.obtainMessage(HelloThreads2.PACKET_CAME,sentence).s
endToTarget();
To the
} catch (Exception e){
socketOK = false;
Message
Handler in the
}// try

main Thread

}// while(socketOK)

@2010 Mihail L. Sichitiu

Android Manifest

To be able to use the Internet (open sockets) and to read our


own IP address (from the WiFi Manager):

<uses-permission android:name="android.permission.INTERNET" />


<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE" />

@2010 Mihail L. Sichitiu

10

You might also like