Android Adventures – Keeping alive a Bluetooth connection

Continuing my adventures into the Android domain, I wanted to have a Bluetooth connection between two nodes, going indefinitely, until one node sends a termination signal. Between the time of initializing the connection, and termination, the two nodes may exchange messages at random intervals.Now, the Bluetooth chat example provided in
http://developer.android.com/resources/samples/BluetoothChat/index.html is very helpful. I did use some of the code, but my client connection was defined in the Activity class itself, as a inner class extending Thread:

public class MyActivity extends Activity {
 
 //some code here that does the work in the activity
 
 
   private class MyThread extends Thread {
        private final BluetoothSocket socket;
private final BluetoothDevice device;
private WorkerInfo worker;
        public MyThread(WorkerInfo pInfo) {
BluetoothSocket tmp = null;
device = pInfo.getDevice();
worker = pInfo;
try {

UUID uuid = UUID.fromString(CommonConstants.WORKER_UUID);
tmp = device.createRfcommSocketToServiceRecord(uuid);

} catch (IOException e) {
}
socket = tmp;
}

public void run() {
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
socket.connect();
worker.setSocket(socket);
worker.isConnected = true;
if (D)
Log.d(TAG, “connected”);

String devName = socket.getRemoteDevice().getName();
String devAddr = socket.getRemoteDevice().getAddress();
Log.d(TAG, “connected to ” + devName + “:” + devAddr
+ “at DelegatorThread ” + this.getId());
Thread t = new Thread(new Reader(socket.getInputStream()));
t.start();
} catch (IOException connectException) {
return;
}
}

  }

}

I would call the MyThread to start() at the click of a Button, and then open an OutputStream on another Button click and write to the other node. This went fine. Then after several minutes, I wanted this to read from the other device. This is where it went wrong.
For some reason, after writing, my connection just dies. When the other device tries to write, it gets a connection reset by peer exception. However, if instead of waiting for several minutes, the other device wrote back immediately, the connection is kept alive.

there were two things I could do :

  1. Keep the connection alive by exchanging random bytes of data. I tried this out by implementing a KeepAliveClient thread and a KeepAliveServer thread. These would write and read small messages indefinitely till the actual message/s is/are ready to be transmitted. This could be done so that the actual messages are preceded by a special pattern so that the reader knows it has to switch from KeepAlive mode to actual Reading mode. After reading the actual message, it again switches back to KeepAlive mode.
  2. Share the Bluetooth object instance across Activities using the singleton model as suggested here. I implemented this version as well:

Put the MyThread into a seperate public class, and instantiate and start this thread from a singleton   class.  I call the method in singleton class from my Activity. This worked as well.

I’m not entirely sure the reason a singleton object method works though. Will continue working in the 2nd method because obviously it is more efficient (not having to keep transmitting), and hopefully things will clear out in future experiments 🙂

29 thoughts on “Android Adventures – Keeping alive a Bluetooth connection

  1. Nash_Node

    Yadi yadi ya…ok miss PHD, I got a question for you.

    I need to install sinhala unicode on a motorola xoom…running android 3.1 honeycomb

    I guess I got the last part correct.. I am no techie geek like you chapes 🙂

    I guess you already know what xoom is, but just in case, its the iPad ass kicking version from Motorola 🙂

  2. niroshini

    @Nash
    Hey you’re back from the dead!
    😛

    I haven’t actually tried this, but it looks as if someone else has already tried with Nexus one. Take a look here:
    http://sinhala.kalingasblog.com/2010/07/25/sinhala-unicode-on-android-google-nexus-one/

    The link above explains how to do it to Android 2.2. For how to root a Honeycomb, take a look here:
    http://androidadvices.com/root-motorola-xoom-honeycomb/
    I guess the other parts (installing the font) holds the same for Honeycomb.

    Whatever you do, do backup all your contacts and data. Rooting could backfire and erase everything!

    Anyway let me know how it goes..I might try to do this on my Androids too.

  3. niroshini

    Yep it looks like u’d have to be in sad face mode…
    You should make a complaint to Google/Motorola. There should be a forum somewhere. The more people voice their concerns, the better. It’ll hurry them into providing the upgrades.

  4. Valentina

    Wonderful beat ! I would like to apprentice while you amend your site, how could i subscribe for a weblog site?

    The account helped me a applicable deal. I had been tiny bit acquainted of
    this your broadcast offered shiny transparent idea

  5. maison à vendre pierrefonds

    Hello there, just became alert to your blog through Google,
    and found that it’s really informative. I’m going to watch out for brussels.

    I’ll be grateful if you continue this in future. Many people will be benefited from your
    writing. Cheers!

  6. https://lesbiansexgif.com

    He was, Miss Farley defined, not formally concerned within the interview, but had expressed an curiosity to
    take a seat in. Nervously, I set out for my interview,
    feeling foolish and really self-conscious. Miss Farley defined that this was the secretarial pool, the place I’d begin out if I used to be successful in my
    interview. Actually, somebody did, a boy my very own age,
    who was checking me out but doing nothing more, a lot to my relief.

    Moms A CHEATER – Hot Milfs Who Cheat On Their Hubbies In Milf Videos & Milf Photos.
    Unusual teen sex images and cute girlfriends who
    is not shy to indicate their erotic and nude pics!
    To not say I wouldn’t like to have the show picked up by a business entity.
    Don’t say to your self, “the man is the spiritual head, he ought to lead in this.” If he’s not leading, you take the lead.
    Scientists predict digital reality will soon take over the
    porn trade, allowing for extra immersive experiences.
    The Africans in South Africa are malfunctioning as a nation because for over four hundred
    years, the fixed in the reality of Africans has been that of being servants, slaves and segregated topics of different European rule.
    I confirmed that I had moved into the realm lately and
    was sharing a flat with my twin brother, who, by the
    way, was being interviewed for a trainee broker spot at Abbotts later as we speak.

  7. 먹튀검증사이트

    Greetings from Florida! I’m bored at work so I decided to check out your website on my iphone during lunch break.
    I enjoy the knowledge you present here and can’t wait to take a look when I get home.
    I’m amazed at how quick your blog loaded on my phone ..

    I’m not even using WIFI, just 3G .. Anyways, awesome blog!

    My web blog 먹튀검증사이트

  8. garden bridges for sale australia

    Just want to say your article is as astonishing. The clarity in your put up is just cool and
    i can think you’re an expert in this subject. Fine with your permission allow me to grasp your RSS feed to keep up
    to date with forthcoming post. Thank you 1,000,000 and please carry
    on the enjoyable work.

  9. 마진거래

    I’m really enjoying the design and layout of your website. It’s a very easy on the eyes which makes it much more enjoyable for me
    to come here and visit more often. Did you hire out a designer to create your theme?
    Great work!

    My web site :: 마진거래

  10. biggirlpussy.com

    ※未滿十八請勿瀏覽點閱※
    微信:aliceteas
    台中七期雞éb>,台中七期全套服åb>,台中七期外送茶經éb>,
    台中七期喝茶吃éb>,台中七期打çb>,台中七期茶èb>,
    豐原個åb>,豐原上åb>,豐原雙éb>,豐原毒éb>,

  11. Japan Sex Tube Online

    Hi there! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing
    months of hard work due to no data backup. Do you have any solutions to prevent hackers?

  12. 먹튀검증

    Hey! This post couldn’t be written any better! Reading this post reminds me of my good old room
    mate! He always kept chatting about this. I will forward this
    page to him. Fairly certain he will have a good read.

    Many thanks for sharing!

    Also visit my web-site 먹튀검증

  13. Watch Jav Free HD

    I am really enjoying the theme/design of your site.
    Do you ever run into any browser compatibility problems?
    A couple of my blog readers have complained about my website not operating correctly in Explorer but looks great
    in Safari. Do you have any ideas to help fix this problem?

  14. zShot App

    Oh my goodness! Impressive article dude! Thank you so much, However I
    am having troubles with your RSS. I don’t understand why I can’t subscribe to
    it. Is there anyone else getting similar RSS problems?
    Anyone that knows the answer can you kindly respond? Thanks!!

  15. 사설토토

    Very nice post. I simply stumbled upon your blog and wished
    to say that I’ve truly loved surfing around your weblog posts.
    In any case I will be subscribing in your feed and I hope you write again soon!

    My blog – 사설토토

Comments are closed.