Issue with detecting phone orientation for android - infinite loop

Issue with detecting phone orientation for android - infinite loop

I need my mobile site setup that landscape and portrait orientation is detected.  Initially I am just using alert messages to test this.  This doesn't seem to be a problem on the iphone or the blackberry torch - I get a single pop-up displaying the correct rotation when the phone is turned. However,  on the android the pop-up functionality gets into an infinite loop with the pop-ups.  I've tried 3 methods as shown below but I get the same result in each.

Test 1

detectOrientation();
window.onorientationchange = detectOrientation;

function detectOrientation(){
    if(typeof window.onorientationchange != 'undefined'){
        if ( orientation == 0 ) {
             //Do Something In Portrait Mode
             //alert(0);
        }
        else if ( orientation == 90 ) {
             //Do Something In Landscape Mode
             //alert(1);
        }………

Test 2

(From a site dealing specifically with android phones)

var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, function() {
    alert('window.orientation + " " + screen.width);
}, false);


Test 3

$(window).bind( 'orientationchange', function(e){
      alert( 'orientation: ' + e.orientation);
    });

I did also just try to run the function I required for each orientation rather than the alert, but whilst this works on iphone/blackberry it doesn't on Android (presumably because of the loop issue)? Any help much appreciated.