Android Intents, registerReceiver, BroadcastReceiver, updating GUI elements from threads

August 12th, 2011

First, let me make one thing clear.  I have Java.  I think that there is something wrong with the way people who code java think.  It’s like they have to make things as complicated as possible, as verbose as possible, and as convoluted as possible for no reason.

I had a simple goal, and that was to have a background thread receive some data and update a text field in an “Activity”.  There were plenty of webpages that attempted to describe how to do it, referring to explicit intents, to modifying the Manifest.xml file, and all sorts of other jargon – but no clear examples.  I came across dozens of posts from people trying to do the same thing I wanted to do, but no answers.  I spent about 4 hours trying to piece together a method that worked. 

Hopefully, this simple explanation will help someone..

If you want to send data from one thread to another you can do it through a messaging protocol, and encapsulate data in that message if needed.  One big complication is that the messaging can occur across applications, it can be directed at a specific target if you know it exists, or it can be ambiguous and you figure something will deal with it.  The messages can also invoke an application (“Activity”) to do something.

What I’m going to describe is how to send a message from one part of an application to another – with the typical goal being to send data to the active “activity” to display data or somesuch.

 

1. In the activity where you want to receive messages, you need to create a class within the activity class (I have no idea what the java developers were smoking to come with this idea) that extends BroadcastReceiver().  You then want to override onReceive() to contain the business logic.

 

public class ActivityClass extends Activity {

  private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals("net.reza.SET_BATT")) {
            setBattery(intent.getIntExtra("value", 0));
        }        
    }
  };

  /* rest of your code */

}

In this example, I’m creating  mReceiver which is a BroadcastReceiver but I am modifying the onReceive() method.  In the method, I’m checking to see if the activity string is equal to “net.reza.SET_BATT”.  This can be anything.  There are some standards that are meaningless.  Use whatever you want.  I think it’s called an intent or intent-filter.  I’m going to call it a ‘tag’ for clarity.

2. You need to register that mReceiver is capable of handing the “net.reza.SET_BATT” tag.  There are a bunch of places to do this in your code.  I stuck it in the onCreate() method for the Activity class.

 

@Override

public void onCreate(Bundle savedInstanceState) {
  IntentFilter ifilt = new IntentFilter("net.reza.SET_BATT");
  registerReceiver(mReceiver, ifilt);

  /* more code */

 

A lot of the documentation said you need to modify the Manifest.xml file and stick it in there, but that was a mess and not obvious how to make it work.  Defining it this way is /much/ easier, and in my mind, much more manageable.  Why do java people love XML so much? 

And I have no idea why they call these tags “intent-filters” but they do.  Based on my code, you don’t need to bother with the action.equals() line, as the only time it will be called is if that tag is registered with registerReceiver(), and I’ve only registered that one tag.   But if you register multiple tags with the same BroadcastReceiver then you should check to see which one is being called.

 

3. You need to invoke that tag.  This can be done anywhere, as far as I know.  Even from another application.  In my case, it’s from a background thread that monitors the battery voltage by polling a device over bluetooth. 

public class BatteryMonitor extends Thread{

Context context;

public BatteryMonitor(Context y) {

  this.context = y;

}

 

public void run() {

  /* some code */

  Intent i = new Intent("net.reza.SET_BATT");
  i.putExtra("value", bat);
  this.context.sendBroadcast(i);

  /* more code */

}

 

Couple things here.  First, I still have no clue what a context is, who owns it, and how to use it properly.   I kept trying different things till it worked.  I passed the output of getBaseContext() to the constructor of the background thread, and that seemed to work.  I think some other options are getContext() and getApplicationContext(), so try those too.  Please post a comment if you know what’s going on.  

So we create an Intent with the same tag.  We can then stick extra data in there – in my case, I add an int. And then you call the sendBroadcast() method from the context object to make it go. 

 

I now need to go write some more code in C to cleanse my mind from all this gibberish…

Electronics

Skunkworks Project–Modern Art PCB

July 10th, 2011

Been busy the past month with a secret project.  Still in stealth mode, but the layout looked like modern art, so I thought I would share…

 

image

Electronics

Bluetooth enabled multifrequency bioimpedance spectrometer for hydration monitoring.

June 5th, 2011

P1040489

I finally had a chance to assemble this PCB.  Alas, I ordered an SO8 package for a part accidentally and had to stick it on a daughterboard.  Will replace with the right part.  Designed to scan complex bioimpedance from 1k-100kHz and communicate with a handheld tablet over bluetooth.  I’ve moved away from the CSR ICs to using these packages as the BlueCore 3 that we were using became more expensive than these modules, and the modules are a lot simpler to solder.  I’m planning on moving to the BlueCore5 for future designs – can get power consumption down to <10mA (if you believe the datasheet) at 115kbps.

Electronics

Mobile Health 2011, ESC 2011, HCI-DC 2011 all in a week

May 4th, 2011

Its been a busy week for me, I was in DC last week for a conference, san jose yesterday for an embedded systems conference and now in stanford for the mobile health conference. Last night I ended up at a super-geek dinner which was cool though the venue was not optimal. I got a chance to meet Grant Imahara from the mythbusters fame, the founder of iFixit, and some other geek VIPs. It was more of a show and tell with all sorts of gadetry in the middle of a restaurant, including a rc helicopter flight that almost srt off the sprinklers.

They just started the talks at the MH2011 conf. So far I think that there are a ton of interesting people here, but I’m a bit dissapointed with the first 3 talks. Ill be posting some more as the conference progresses.

Electronics

Bioimpedance Spectroscopy Boards Arrived

May 2nd, 2011

I had some PCBs made up to do some bioimpedance spectroscopy for edma detection through the cole-cole model. One set has an MCU & space for a bluetooth module meant to communicate with an android tablet.  The other is a stand-alone module that I’m going to try and interface directly with a microtouch avr touchscreen.

 

  bioZ pcb 001

 

These will go from 1kHz to 100kHz.  If you notice the big PCB, I made the VIAs have a teardrop shape – they look cool.  It’s based on my design for a fixed 50kHz device for impedance plethysmography that I use to measure respiration.  Fun stuff!

Electronics

Random Slow-Carb Recipes

February 8th, 2011

This slow-carb diet has forced me to cook a lot more, and I’ve enjoyed the process.  I thought I would share a couple of the dishes that I enjoy – and that are a lot more interesting than the ones that Tim (ala 4-Hour Body) recommends.  I will not present this in the typical recipe format, rather, it’s more of a technique you can apply.

First, great simple way to prepare chicken/pork.  This cooks fast, gives juicy results, and tastes great.  First, the marinade – super simple – super fast.  Sriracha Hot sauce & Soy sauce.  I bought this organic kikoman soy sauce and really like it.

 

P1040408

 

Add a bunch (I use about equal parts, but adjust to suite your taste) to meat (I like using the costco frozen tenderloins).

 

P1040407

 

Just a few minute seems to work, because we will then fry it in some oil.  Doesn’t have to cover the meat.  The meat absorbs none of the oil, cooks fast, and is super juicy.  I also use the same method for pork cutlets.  I sometimes add an egg yolk if I want it to have more of a battered feel, though it’s not needed.

 

I have also decided I can’t stand canned beans anymore.  Ugh.  I’ve tried my hand at lentils (someone posted a recipe that sounded great and involved bacon, but it didn’t come out all that great).  So I hit up a local Indian grocery store and picked up…

 

   P1040406

That, 1/2 and onion, a tomato, and some lentils

P1040405

and I have some simple and great tasting lentils.  Super cheap too if you figure the cost of ingredients.   It takes about an hour or so worth of cooking, but you can make bigger batches and save.  The instructions require a scale, which I had.  I like cooking with a scale more than the volumetric measures we usually use.  Seems more scientific Smile

 

Finally top off with what I’ve found to be a veggie that I’ve not gotten tired of – microwaved broccoli with mayo.  

 

 P1040410

 

Super tasty, and if you cook the lentils in advance, less than 15 minutes from start to finish.

diet, slow-carb , , ,

One more day

January 26th, 2011

I’ve been stressed out about what’s going to happen tomorrow.  For almost 3 years I’ve been thinking about tomorrow.  It’s a simple exam that in the history of my department, no one has failed.  I present a research project, show I know the background to the material, and I pass.  However, I’ve managed to get advice from a set of people who have the most disparate ideas about what said proposal should entail.  That might not seem like a bad idea, but I’ve probably put together 3 totally different project, with multiple revisions of each that take a whole different slant on the material.  To nail that point home, I found out yesterday that the cumulative sum of months of work was “just not going to work” and I was advised to learn a multitude of new mathematical frameworks to be able to come up with an answer that really wouldn’t address my hypothesis.  And the exam date was fixed.

 

What ensued:

  1. Panic.  I felt like I was the captain of a plane that was on fire.  I wasn’t dead but I had to do something.
  2. I decided pursue all my options simultaneously.  These included
    • call library to find relevant mathematical and psychological textbooks.  Probability of mastering (which was required) the new material in 48 hours: 3%. 
    • Email various departments looking for a tutor to help with the material.  (10% success probability)
    • Try to figure out a way to slice and dice my content such as the “it’s not going to work” condition goes away.  This involved asking for a number of people to help in a brainstorming session.

    Of the three options, the third won out and 5 hours later, I had a 100% different presentation that utilized 20% of the material I started out with.  An additional 7 hour of work on the slides and I had a first pass ready.  4 hours of sleep later and a 30 minute drive – and I was back on campus working the written part of the project.  I found a tutor who offered to help and we covered the relevant material in no time.  If someone explains content at the right level, I can digest it very quickly.  For example, I love “The Darker Side” – it does an amazing job of explaining mixed signal electronic design.  He’s also the only good author left on Circuit Cellar’s payroll. 

    In any case, the exam is tomorrow.  One thing I’ve learned though all this is about stress, both the theory, about my experiences, and my developed theories (one of which I’ll be presenting on).  And what’s amazing is that I’ve been able to control the physical manifestation of stress – I’m so much better at being able to deal than I was just 3 months ago.  I’m really not stressed about tomorrow, even though I should be. 

    Electronics

    Slow-Carb Diet Update–Day 7

    January 16th, 2011

     

    I think I’m going to start posting some details about the progress of my diet through the course of it as this sort of info might be helpful to others.   I had my 1st “bing” day yesterday, which is sanctioned by the diet.  I decided to try to go full bore and see how it effected me.  My breakfast consisted of:

    • waffles
    • fried chicken
    • 2x sausage & egg sandwiches
    • grits (didn’t like it, didn’t eat much) – how are these supposed to be eaten?
    • 2x 16oz glasses of sweet tea

     

    As good as it tasted, it made me feel horrible for the rest of the day.  I had a headache and my body hurt.  It’s amazing how bad sugar is for you.  The evening was filled with more goodness including crab cakes, bolgogi beef, chicken meatballs, pan-fried mac and cheese balls, shrimp with bacon, sausage burgers, beer, wine, bourbon.   The results:

     

    image

     

    Now, if the diet works, by Tuesday I should return to my post-binge weight.  Sarah and I went to Safeway (how I hate that place) and I bought more veggies than I ever had before in my life.  Trying to follow the paradigm of “use bag of frozen veggies” just didn’t cut it and I need to get some variety.  So for lunch I had two “slow-carb” burritos that consisted of a large piece of lettuce, layer of refried beans, garlic pulled pork from last week, sautéed green beans/onions/garlic/spring onions, peppercinis, avocado, and habanero salsa (finally found a safeway salsa that I liked).  And it was really good – I didn’t miss the bread at all.  

     

    I’m really enjoying the cooking that I’m doing for this diet, as I’m usually too lazy to cook.  I’ve found it’s been a lot better on the wallet but a huge pain in the ass to clean up.  The dishwasher runs like 2x/day now. 

     

    And tonight – safeway had a great sale on Dungenous crab  — so I’m going to try to make a crab salad with homemade mayo (all the stuff in the store had some sugar added).   I’ll probably add some bacon to it as well. 

    Personal, diet , ,

    My attempt at implementing Tim Ferriss’ Slow-Carb Diet

    January 14th, 2011

    I’ve been working too hard at graduating and a number of other projects where I found I wasn’t going to the gym nearly as much as I used to.  As a result, I started feeling unhealthy, but I also didn’t believe in dieting.  That was till I saw a blog entry on gizmodo.com about Tim’s book, the 4-hour body.  It’s not a diet book, but rather a somewhat scientific look at how to hack many aspects of your body – and I bought his pitch.  It made sense to me, and it seemed like an approach that I could follow. 

    The chapter that talks about the diet is essentially converted from this blog entry.  I’m not going to bore you with the details, but I’m trying to be a bit methodical about the progress and want to document it.  Essentially, it’s 4 meals a day of lots of beans (I never want to eat beans again after this).  He also stresses keeping the meals simple (read: boring) and the same.  He argues it’s simpler that way.  Unfortunately,  following that advice will get me disinterested quickly from the diet.  I need variety.  I just finished cooking the garlic pork dish from this cookbook I found online.   

    Anyhow, I’m doing pretty well though I accidentally violated one of the rules and had some fruit juice.  And I’m drinking some whiskey instead of wine right now (thanks diQ for leaving that bottle behind).  But so far I’m on track to hit my goal of 20lbs in 30 days.  I’m also following a regiment of a ton of supplements that he suggests – 13 pills a day no less at a cost of $75/month for the supply.  Normally I’m not into that kind of stuff, but there’s something cool about the thought of hacking my body, so I’ll give I a shot.  Here’s the data, though I started right after finishing 3 days of my unintentional food-poisoning diet which I dropped 5lbs over 3 days.  I’m actually less now than I’ve been in years.  I’m going to start weight training again after I hit 170, but my body puts on muscle fast and I don’t want to see my weight increase (it’s a motivational thing).

    image

     

    image

    Personal , , ,

    printf in arudino works.

    December 21st, 2010

    I’ve always had to deal with the fact that printf() is missing from the arduino environment.  I would have to come up with these huge blocks of code consisting of multiple Serial.print() commands to put together a simple message.  Well, no more!  It seems that printf works just fine, and for some unknown reason, it’s just not used or talked about. 

     

    In order for it to work, you only need to specify a target for STDOUT by adding this function..

     

    int my_putc( char c, FILE *t) {
      Serial.write( c );
    }

     

    and inside the setup() function you need to point to that function

     

    void setup() {
    …
    fdevopen( &my_putc, 0);
    }

    That it!  Now printf() works!

     

      Serial.println("START");
      fdevopen( &my_putc, 0);
      printf("hello, world!");

     

    image

     

    Why this isn’t documented, I have no idea!

    Electronics, Software ,