Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

The part of my code that deals with threading. The sendMessage() method can be called from any thread and at any time. It posts a new message to send to the message queue and starts the sender thread if it isn't running. The sender thread polls the queue with a timeout, and processes the messages. If there are no more messages in the queue, the thread exits.

View SMS Sender thread
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
private final LinkedBlockingQueue<Message> messageQueue = new LinkedBlockingQueue<Message>();
 
// The sender argument is an enum describing who sent the message: the user, the app, or the person on the other end.
public void sendMessage(String address, String message, Sender sender) {
messageQueue.offer(Message.create(address, message, sender));
startSenderThread();
}
 
private Thread senderThread;
 
private void startSenderThread(){
 
if(senderThread == null || !senderThread.isAlive()){
senderThread = new Thread(){
@Override
public void run() {
loopSendMessage();
}
};
 
senderThread.start();
}
}
 
private void loopSendMessage(){
Message queuedMessage;
 
while(!Thread.interrupted()){
try {
queuedMessage = messageQueue.poll(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
EasyLog.e(SMSSenderDaemon.this, "SenderThread interrupted while polling.", e);
continue;
}
if(queuedMessage != null)
sendOrQueueMessage(queuedMessage);
else
break;
}
}
 
// Queue in this context means storing the message in the database
// so it can be sent later.
private void sendOrQueueMessage(Message message){
//Irrelevant code omitted.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.