How I send multiple SMS' in one program? - java

I want to send multiple SMS' via using smslib. I make a Java class to send SMS in a loop. But it works only one time. then it returns the following exception:
org.smslib.GatewayException: Comm library exception:
java.lang.RuntimeException: javax.comm.PortInUseException:
Port currently owned by org.smslib
at org.smslib.modem.SerialModemDriver.connectPort(SerialModemDriver.java:102)
at org.smslib.modem.AModemDriver.connect(AModemDriver.java:114)
at org.smslib.modem.ModemGateway.startGateway(ModemGateway.java:189)
at org.smslib.Service$1Starter.run(Service.java:276)
This is my class:
import javax.swing.JOptionPane;
import org.smslib.AGateway;
import org.smslib.IOutboundMessageNotification;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.modem.SerialModemGateway;
public class SendSMS1 {
private static String id;
private static String port;
private static int bitRate;
private static String modemName;
private static String modemPin;
private static String SMSC;
public static void doIt(String number, String text) {
try {
OutboundMessage msg;
OutboundNotification outboundNotification = new OutboundNotification();
SerialModemGateway gateway = new SerialModemGateway(id, port, bitRate, modemName, "E17u-1");
gateway.setInbound(true);
gateway.setOutbound(true);
gateway.setSimPin(modemPin);
Service.getInstance().setOutboundMessageNotification(outboundNotification);
Service.getInstance().addGateway(gateway);
Service.getInstance().startService();
msg = new OutboundMessage(number, text);
Service.getInstance().sendMessage(msg);
System.out.println(msg);
Service.getInstance().stopService();
} catch (Exception ex) {
if (ex.getStackTrace()[2].getLineNumber() == 189) {
JOptionPane.showMessageDialog(null,
"Port currently owned by usb Modem's application. \n Please close it & run the programm again.",
"Port Exception",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
} else {
JOptionPane.showMessageDialog(null,
ex.getMessage(),
"Sending faile",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
}
public static class OutboundNotification implements IOutboundMessageNotification {
public void process(AGateway gateway, OutboundMessage msg) {
System.out.println("Outbound handler called from Gateway: " + gateway.getGatewayId());
System.out.println(msg);
}
}
public static void main(String[] args) throws Exception {
String number = "+94772347634", text = "Hello world";
modemName = "Huwawi";
port = "COM4";
bitRate = 115200;
modemPin = "0000";
SMSC = "+947500010";
for (int i = 0; i < 5; i++) {
SendSMS1 app = new SendSMS1();
app.doIt(number, text);
}
}
}
Please give me advice, what should I do differently?

I don't know the smslib, but I imagine everything until startService should only happen once, not each time you want to send a message, as follows:
class SendSMS1
{
public SendSMS1(String modemName, String port, int bitRate,
String modemPin, String SMSC)
{
OutboundNotification outboundNotification = new OutboundNotification();
SerialModemGateway gateway = new SerialModemGateway(id, port, bitRate, modemName, "E17u-1");
gateway.setInbound(true);
gateway.setOutbound(true);
gateway.setSimPin(modemPin);
Service.getInstance().setOutboundMessageNotification(outboundNotification);
Service.getInstance().addGateway(gateway);
Service.getInstance().startService();
}
public static void doIt(String number, String text) {
try {
OutboundMessage msg = new OutboundMessage(number, text);
Service.getInstance().sendMessage(msg);
System.out.println(msg);
Service.getInstance().stopService();
} catch (Exception ex) {
if (ex.getStackTrace()[2].getLineNumber() == 189) {
JOptionPane.showMessageDialog(null,
"Port currently owned by usb Modem's application. \n Please close it & run the programm again.",
"Port Exception",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
} else {
JOptionPane.showMessageDialog(null,
ex.getMessage(),
"Sending faile",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
String number = "+94772347634", text = "Hello world";
SendSMS1 app = new SendSMS1("Huwawi", "COM4", 115200, "0000", "+947500010");
for (int i = 0; i < 5; i++) {
app.doIt(number, text);
}
}
}

You must remove the gateway.
can use this-
Service.getInstance().removeGateway(gateway);
you should insert it in doIt method, after - Service.getInstance().stopService();

Change this.It's Working
public static void main(String[] args) throws Exception {
Calendar now = Calendar.getInstance();
String ar=(dateFormat.format(now.getTime()));
String text = "We are the Future of Science "+" "+ar;
SendSMS app = new SendSMS("Huawei", "COM20", 115200, "0000", "+9477000003");
for (int i = 0; i < 1; i++) {
String[] numbers = {"+num","+num","+num","+num","+num","+num","+num","+num"};
for (String item : numbers) {
Service.getInstance().startService();
app.doIt(item, text);
Service.getInstance().stopService();
}}
}

Related

Publisher MQTT client stops to work in Subscriber's Callback. (PAHO JAVA)

I'm trying to implement a fake broker (actually it is an mqtt publisher client in an mqtt subscriber's callback). There are 3 separated publisher clients which are publishing random numbers between 0 and 1. This fake broker just summarizes this random numbers, and publishes away to an other topic. (Maybe not in the right way, but for now it is ok) This solution is working but after a few incoming messages this broker stops to work. I Tried to debug it, but I found only ClassNotFound Exceptions... Here is my FakeBroker and it's Callback implementation.
public class FakeBroker implements Runnable{
public static final String BROKER_URL = "";
public static final String TOPIC_FAKE_A = "";
public static final String TOPIC_FAKE_B = "";
public static final String TOPIC_FAKE_C = "";
public static final String USER_NAME = "";
public static final char[] USER_PSW = "".toCharArray();
private MqttClient client;
private MqttConnectOptions options;
private SubscriberCallback callback;
public FakeBroker() {
options = new MqttConnectOptions();
options.setUserName(USER_NAME);
options.setPassword(USER_PSW);
options.setCleanSession(false);
callback = new SubscriberCallback();
try {
client = new MqttClient(BROKER_URL, MqttClient.generateClientId()+"-sub");
client.setCallback(callback);
} catch (MqttException e) {
e.printStackTrace();
System.exit(1);
}
}
public void start() {
try {
client.connect(options);
System.out.println("Fake Broker are connected to the cloud.");
client.subscribe(TOPIC_FAKE_A);
client.subscribe(TOPIC_FAKE_B);
client.subscribe(TOPIC_FAKE_C);
} catch (MqttException e) {
e.printStackTrace();
}
}
#Override
public void run() {
start();
}
}
And here is it's Callback
public class SubscriberCallback implements MqttCallback {
public static final String BROKER_URL = "";
public static final String TOPIC_FAKE_BROKER = "";
public static final String USER_NAME = "";
public static final char[] USER_PSW = "".toCharArray();
private MqttClient client;
private MqttConnectOptions options;
private int counter = 1;
private int result = 0;
public SubscriberCallback() {
try {
client = new MqttClient(BROKER_URL, "4-pub");
options = new MqttConnectOptions();
options.setPassword(USER_PSW);
options.setUserName(USER_NAME);
} catch (MqttException e) {
e.printStackTrace();
}
}
#Override
public void connectionLost(Throwable throwable) {
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
System.out.println("Message Arrived. Topic " + topic + " message: " +mqttMessage + " ---- Message Counter: " + counter);
int number = Integer.parseInt(mqttMessage.toString());
result += number;
if (counter%3 == 0) {
publishAway(new MqttMessage(Integer.toString(result).getBytes()));
result = 0;
}
incrementCounter();
}
private void publishAway(MqttMessage mqttMessage) throws MqttException {
client.connect(options);
final MqttTopic topicFakeBroker = client.getTopic(TOPIC_FAKE_BROKER);
topicFakeBroker.publish(mqttMessage);
client.disconnect();
System.out.println("Fake broker got the message " + mqttMessage + " and published away to" + topicFakeBroker.getName());
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
private void incrementCounter() {
counter++;
}
}
Of course I use valid BROKER_URL and TOPICS but these informations are confidential. Thanks for Your answers! :)

JAVA: Serialization works good on Local Machine but when I do this in LAN it does not output correct

I want to send an object having OS Name to a server. This OS Name output should be of PC sending object but it displays OS Name of PC running server..
Here is my code :
//Client : it can send data i.e. object to server
class Client
{
private Socket socket = null;
private ObjectOutputStream outputStream = null;
public Client(String con){
System.out.println("conn value: "+con);
java.util.Timer t = new java.util.Timer();
try{
socket = new Socket(con, 27051);
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
try {
outputStream = new ObjectOutputStream(socket.getOutputStream());
SI sysinfo=new SI();
outputStream.writeObject(sysinfo);
System.out.println("Sent Data: "+sysinfo.otherInfo());
} catch (Exception se) {
t.cancel();
}
}
}, 0, 1);
}
catch(Exception em)
{
}
}
}
//Server class: should receive data from client
class Server extends SwingWorker<Void,Void>{
Socket csocket=null;
protected Void doInBackground() throws Exception {
final ServerSocket ssock = new ServerSocket(27051);
System.out.println("Server Listening..!!");
while (true) {
try{
Socket sock = ssock.accept();
new Thread(new Server(sock)).start();
}
catch(Exception e){
System.out.println("unabke to create socket");
}
}
}
Server() throws Exception{
doInBackground();
}
Server(Socket csocket) {
this.csocket=csocket;
Thread t1=new Thread(r1);
t1.start();
}
Runnable r1=new Runnable()
{
public void run() {
try {
System.out.println("Run initated");
while(true)
{
if(csocket.isClosed())
{
break;
}
else{
System.out.println(csocket);
ObjectInputStream inStream = new
ObjectInputStream(csocket.getInputStream());
SI sysinfo= (SI) inStream.readObject();
System.out.println("Received: "+sysinfo.otherInfo());
System.out.println(ObjectStreamClass.lookup(sysinfo.getClass()).getSerialVersion
UID());
}
}
}
catch (Exception e) {
System.out.println("Exception"+ e.getMessage());
}
}
};
}
//class undergoing serialization
public class SI implements Serializable
{
private static final long serialVersionUID = 1L;
String otherInfo()
{
OperatingSystemMXBean bean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
String os_name=bean.getName();
return os_name;
}
}
//class A: It has main function and it executes first and user decides whether he/she want to be in server mode or in client mode. As user cannot be in 2 modes simultaneously..
class A
{
public static void main(String[] args) throws Exception
{
System.out.println("Enter 0 for Server 1 for Client Mode");
Scanner s=new Scanner(System.in);
int i=s.nextInt();
if(i==0)
{
Server ser=new Server();
ser.execute();
}
else if(i==1)
{
System.out.println("Enter IP");
String conn=s.next();
Client c=new Client(conn);
}
else
System.out.println("Invalid Selection exit..");
}
}
As I wrote in my comment you must transfer the data, not the function. Some sample code below...
First, change your SI class as follows:
public class SI implements Serializable {
private static final long serialVersionUID = 1L;
private String osName;
public void setOsName(String osName) { this.osName = osName; }
public void getOsName() { return this.osName; }
}
Second, modify your client to first determine the OS and the build the SI object...
...
OperatingSystemMXBean bean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
String osName=bean.getName();
SI sysinfo = new SI();
sysinfo.setOsName(osName);
...
outputStream.writeObject(sysinfo);
...
Third, modify your server accordingly.

How do I send a message to a specific client(JAVA)

I want to send a message to a specific client:
/w hey there.
X:(priv)Y:hey there(what X sees in the console)
This is my code.When I type it like the upper example nothing shows neither on the specific client's console neither on the server.I don't understand why,because I also have a list of users that are connect in the Server class.
import java.net.*;
import java.io.*;
public class ServerPeer extends Thread{
Socket _socket;
public ServerPeer(Socket _socket) {
this._socket = _socket;
}
public void sendMessage(String _username,String _message) throws IOException {
ObjectOutputStream _obj = new ObjectOutputStream(
_socket.getOutputStream());
_obj.writeObject(new Message(_username, _message));
_obj.flush();
}
public synchronized void run() {
try
{ ObjectInputStream _ois = new ObjectInputStream(_socket.getInputStream());
Message _message;
while (_socket.isConnected()) {
_message = (Message) _ois.readObject();
String divide=_message.getAll().substring(0,_message.getAll().indexOf(":"));
for(ServerPeer sp:Server.listofpeers)
{
if(_message.getAll().startsWith("exit"))
{
_socket.close();Server.listofpeers.remove(sp);
}
if( !(_message instanceof PrivateMessage))
{
sp.sendMessage(divide,_message.getAll());
System.out.println( _message.getAll());
}
else
{
PrivateMessage privatem=(PrivateMessage)_message;
String receiver=privatem.getReceiver();
for(String s:Server.listofusers)
{
if(s.equals(receiver))
{
sp.sendMessage(divide,privatem.getAll());
System.out.println(privatem.getAll());
break;
}
}
}
}
_ois = new ObjectInputStream(_socket.getInputStream());
}
}catch(IOException e){e.printStackTrace();}
catch(ClassNotFoundException e){e.printStackTrace();}
}
}

Convert socket chat to RMI chat

As part of my lab this week I am suppose to convert a socket based chat application to RMI. So far I managed to connect server and client together and transfer data between them but the transfer is not continuous. What I mean is that when the client first connects t the server it broadcasts a message "X has entered the conversation" but that is all. Anything I type after that wont get broadcasted. I am about to pull out my hair. Please help.
public class ChatServer extends UnicastRemoteObject implements ChatMessage {
private static final long serialVersionUID = 1L;
private String sender;
private String message;
private ChatMessageType t;
public ChatServer() throws RemoteException {
super();
}
#Override
public void Message(String sender, ChatMessageType t, String message)
throws RemoteException {
this.sender = sender;
this.message = message;
this.t = t;
}
#Override
public String getSender() throws RemoteException {
return sender;
}
#Override
public String getMessage() throws RemoteException {
return message;
}
#Override
public ChatMessageType getType() throws RemoteException {
return t;
}
public String ToString() throws RemoteException{
String strMessage;
switch (t) {
case SETUP:
strMessage = sender + " has entered the conversation.";
break;
case TEARDOWN:
strMessage = sender + " has left the conversation.";
break;
case MESSAGE:
strMessage = sender + ": " + message;
break;
default:
strMessage = "";
}
return strMessage;
}
// driver.
public static void main(String arg[]) {
try {
ChatServer c = new ChatServer();
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind("Server", c);
System.out.println("Server bound in registry");
} catch (Exception e) {
System.out.println("Server error: " + e.getMessage());
e.printStackTrace();
}
}
}
public class ChatClient implements ActionListener {
// static private Socket c;
static ChatMessage obj = null;
// static private ObjectInputStream in;
// static private ObjectOutputStream out;
static private String name;
static private String host;
static private Integer port;
/**
* Launches this application
*/
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (args.length != 3) {
System.out
.println("Client requires exactly three args to run.");
System.exit(-1);
}
name = args[0];
host = args[1];
port = new Integer(args[2]);
final ChatClient application = new ChatClient();
application.getJFrame().setVisible(true);
try {
System.out.println("client: connecting to server...");
// c = new Socket(host, port);
obj = (ChatMessage) Naming.lookup("//" + host + ":" + port
+ "/Server");
System.out.println("client: connected!");
} catch (Exception e) {
System.out.println("client: " + e.getMessage());
System.exit(-1);
}
try {
// out = new ObjectOutputStream(c.getOutputStream());
// in = new ObjectInputStream(c.getInputStream());
// announce to other clients that you're here
// out.writeObject(new ChatMessage(name,
// ChatMessageType.SETUP, ""));
obj.Message(name, ChatMessageType.SETUP, "");
} catch (Exception e) {
}
// set up the client's listener as an anonymous thread that's
// always running
// new Thread(new Runnable(){
// public void run()
// {
// while(true)
// {
try {
System.out.println(name + ": waiting for data");
ChatMessage m = (ChatMessage) Naming.lookup("//" + host
+ ":" + port + "/Server");
System.out.println(name + ": data received");
application.updateTextArea(m.ToString());
} catch (Exception e) {
}
// }
// }
// }).start();
}
});
}
public void updateTextArea(final String message) {
conversation.setText(conversation.getText() + message + "\n");
// this will guarantee that the bottom of the conversation is visible.
conversation.setCaretPosition(conversation.getText().length());
}
// send button has been pressed, send the message to the server.
public void actionPerformed(ActionEvent e) {
if (send.getText().equals("Send")) {
try {
System.out.println(name + ": sending data");
// ChatMessage m = new ChatMessage(name,
// ChatMessageType.MESSAGE, message.getText());
// out.writeObject(m);
obj.Message(name, ChatMessageType.MESSAGE, message.getText());
message.setText(""); // clear the text box.
System.out.println(name + ": data sent");
} catch (Exception ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
}
}
enum ChatMessageType{
SETUP,
MESSAGE,
TEARDOWN
}public interface ChatMessage extends Remote{
public String getSender() throws RemoteException;
public String getMessage() throws RemoteException;
public ChatMessageType getType() throws RemoteException;
public void Message(String sender, ChatMessageType t, String message) throws RemoteException;
public String ToString() throws RemoteException;
I realize this question is pretty old and you probably figured out an answer for this, but, I thought I'd share an approach I took for going from Java sockets to RMI. Maybe it is useful for others looking to do the same thing.
I basically abstracted out the socket portion into a "Tunnel" object that represents a communication path between hosts. And the tunnel consists of several "channels", that represent a one-way communication between the source and destination.
You can check out more details at my blog here: http://www.thecodespot.com/?p=1

AVD on Windows7 Not able to connect to Linux Server

This pertains to my earlier post "http://stackoverflow.com/questions/8788825/linux-udp-server-unreachable-from-window-7", which has been solved. Now I am moving to my original job of connecting AVD to Linux server.
I am using the following code for connecting to the server
import java.net.*;
class UDPClient {
public final static int DesitnationPort = 9999;
private int mCounter;
private DatagramSocket mClientSocket;
private InetAddress mServerIPAddress;
private byte[] mDataBuffer;
private DatagramPacket mSendPacket;
private DatagramPacket mReceivePacket;
//Constructor
public UDPClient() {
//Time to make the private data good one
mCounter =1;
try {
mServerIPAddress = InetAddress.getByName("192.168.2.2");
}
catch(UnknownHostException e)
{
System.out.println("Host cannot be resolved :( ");
}
System.out.println("Host has been resolved The IP is valid one ");
try {
mClientSocket = new DatagramSocket();
}
catch(SocketException e)
{
System.out.println("Socket could not be created :( ==> " + e.getMessage());
}
System.out.println("Socket has been created ");
String temp = "This is from the Client == To my Dear Sever :) counter = " + mCounter;
mDataBuffer = temp.getBytes();
mSendPacket = new DatagramPacket(mDataBuffer, mDataBuffer.length, mServerIPAddress, DesitnationPort);
System.out.println("Datagram has been made now ");
System.out.println("Data ==>"+ mSendPacket.getData());
System.out.println("Data ==>"+ mSendPacket.getPort());
System.out.println("Data ==>"+ mSendPacket.getSocketAddress());
System.out.println("Data ==>"+ mSendPacket.getLength());
}
public void SendDataToServer(){
try {
if(!mClientSocket.isClosed()) {
String temp = "This is from the Client == To my Dear Sever :) counter = " + mCounter;
mDataBuffer = temp.getBytes();
mSendPacket = new DatagramPacket(mDataBuffer, mDataBuffer.length, mServerIPAddress, DesitnationPort);
mClientSocket.send(mSendPacket);
System.out.println("Send the packet");
mCounter++;
}
else {
System.out.println("Socket is closed");
}
}
catch(Exception e)
{
System.out.println("Could not send the data :( ==> " + e.getMessage());
}
}
public void ReceiveDataFromServer() {
byte[] tembuff = new byte[1024];
mReceivePacket = new DatagramPacket(tembuff, tembuff.length);
try {
if(!mClientSocket.isClosed()) {
mClientSocket.receive(mReceivePacket);
}
else {
System.out.println("Socket is closed");
}
}
catch(Exception e)
{
System.out.println("Could not Receive the data :( ");
return;
}
String data = new String(mReceivePacket.getData());
System.out.println(" Received the Data => " + data);
}
}
This code works well when I simply use the class in java program like this :-
class TryingWithClient {
public static void main(String a[]) {
UDPClient mClient = new UDPClient();
while(true) {
System.out.println("While Starting");
mClient.SendDataToServer();
mClient.ReceiveDataFromServer();
}
}
}
When I use the same code in AVD project I get a Null pointer exception at the following line :-
public void SendDataToServer(){
try {
if(!mClientSocket.isClosed()){ //<==# this call Null exception occurs
After browsing internet & android development sites I came to conclusion that I am missing the GMS / GPS functionality which I added to my AVD. Still I am unable to get any clue about this.
Here is my code which calls the above UDPClient.
public class StreamingProjectActivity extends Activity {
/** Called when the activity is first created. */
//All buttons
//private static final String LOG_TAG = "StreamingTest";
private StreamButton mStreamButton = null;
private UDPClient mClient= null;
class StreamButton extends Button {
boolean mStartStreaming = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onStream(mStartStreaming);
if (mStartStreaming) {
setText("Stop Streaming");
} else {
setText("Start recording");
}
mStartStreaming = !mStartStreaming;
}
};
public StreamButton(Context ctx) {
super(ctx);
setText("Start Streaming");
setOnClickListener(clicker);
}
}//class StreamButton Ends
#Override
public void onCreate(Bundle icicle) {
try {
mClient = new UDPClient();
System.out.println("==========> Client created sucessfully :) <====== ");
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mStreamButton = new StreamButton(this);
ll.addView(mStreamButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
setContentView(ll);
System.out.println("Trying Step 2 now ");
}
catch(Exception e)
{
System.out.println("Activity could not be launched :( ");
}
}
//public StreamingTest()
public StreamingProjectActivity(){
System.out.println("Constructor ====>");
System.out.println("Constructor <====");
}//Constructor
private void onStream(boolean start) {
if (start)
{
mClient.SendDataToServer();
mClient.ReceiveDataFromServer();
try
{
Thread.sleep(4000);
}catch (InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}//onStream
}
Kindly help.
Ok, first of all: never ever print a catched exception with System.out.println("some msg " + e.getMessage()); Please use Log.e(TAG, "my message", e); for that. So you will actually see a stack trace.
Second: I bet that this code throws an error (check if you see the print in your LogCat output):
try {
mClientSocket = new DatagramSocket();
} catch(SocketException e) {
System.out.println("Socket could not be created :( ==> " + e.getMessage());
}
That is the only reason that mClientSocket still might be null. As this call might go wrong, you should consider checking for null before you check if the socket is closed.
The problem in my earlier solution was that I was mixing the GUI & network operations in the same thread which is called "StricMode.ThreadPolicy" (although, my problem is only part of what is mentioned in the jargon).
I was getting these exceptions "android.os.NetworkOnMainThreadException & android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099) " which I could make out only after I applied WarrenFaith's suggestion (Thanks Warren).
These are thrown only on violation of "StricMode".
Solution : Simply separate the UI work from the network. I had to write the following code for this :
enum ClientThreadStates {
eUndefined,
eStopped,
eRunning,
eIdle,
eSendToServer,
eReadFromServer
}
public class ClientThread extends Thread {
private UDPClient mClient= null;
private ClientThreadStates mStateOfTheThread = ClientThreadStates.eUndefined;
private static String mLOG_TAG;
public ClientThread(String s){
mLOG_TAG = s;
mStateOfTheThread = ClientThreadStates.eStopped;
mClient = new UDPClient(s);
start();
}//constructor
public void SetState(ClientThreadStates paramState) {
mStateOfTheThread = paramState;
}
public ClientThreadStates GetState() {
return mStateOfTheThread;
}
private void Action(ClientThreadStates s) {
synchronized(s) {
switch(mStateOfTheThread) {
case eRunning: //fall
case eIdle: break;
case eSendToServer: mClient.SendDataToServer(); break;
case eReadFromServer: mClient.ReceiveDataFromServer(); break;
}
try {
mStateOfTheThread.wait();
}
catch( InterruptedException e ){
Log.e(mLOG_TAG, "Got Exception at wait <==", e);
}
}
}
public void run() {
mStateOfTheThread = ClientThreadStates.eRunning;
System.out.println("In Thread.run .. The State is " + mStateOfTheThread);
while(ClientThreadStates.eStopped.compareTo(mStateOfTheThread) < 0){ //state >stopped
Action(mStateOfTheThread);
}//while
}//run
}//class ClientThread
Finally synchronize on the two threads on the state like this :
private void onStream(boolean start) {
ClientThreadStates State = mClientThread.GetState();
synchronized(State) {
if (start) {
mClientThread.SetState(ClientThreadStates.eSendToServer);
}
else {
mClientThread.SetState(ClientThreadStates.eReadFromServer);
}
try {
State.notify();
}
catch( IllegalMonitorStateException e ) {
Log.e(LOG_TAG, "Got Exception # notify <==", e);
}
}
}//onStream
}//StreamingProjectActivity
Now the code runs perfectly.
Thanks.
Ashutosh

Categories