While loop in Run stops executing
<p>My program operates in a While loop in the activities Run code.  It is reading USB data every 100ms or so.
When a byte in that USB data stream sets, I call this startVoiceRecognitionActivity():</p>

<pre><code>private void startVoiceRecognitionActivity() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recognition Demo...");
        startActivityForResult(intent, REQUEST_CODE);       
}
</code></pre>

<p>The voice recognizer runs fine, my USB data stream While loop keeps running while the voice recognizer does it stuff.</p>

<p>However, after the onActivityResult executes, my While loop is terminated.  I need to stay in this while loop, how can I do that?</p>

<p>EDIT: I have been debugging this and will be showing the current code that is relevant.  It appears that the onActivityReturn disrupts the USB somehow before the program crashes.  I have edited my while loop to show how I am trying to re-establish USB after a voice recognizer call. </p>

<p>With the code shown, after a voice recognizer call with debug running, the code breaks without a breakpoint.  If I resume code execution from there, the program stops just as if I clicked the Terminate button.  Here is my computer screen when execution breaks by itself happens, it appears to be a NullPointerException issue which is still out of my knowledge base.  Hope someone can point me in the right direction.</p>

<p>I am beginning to believe that the Thread [&lt;12> Thread-130] (running) which you see in the image below here, is the culprit.  This thread appears upon return from a voice recognizer call.  I am thinking I need to make sure that execution returns to the original thread after a voice recognizer call but I could be way off here?</p>

<p><img src="http://i.stack.imgur.com/w8cos.jpg" alt="enter image description here"></p>

<p>OR better yet (maybe), is there a way that I can kill the original thread &lt;11> as I am calling the voice recognizer?</p>

<p>WOW, that was it or at least I thought so, all I needed to do was to break; out of the while loop after I started the speech recognizer (I also have to break out of the while loop on a usb request failure).</p>

<p>And, I do not have to start the speech recognizer in a runOnUiThread().</p>

<p>I thought this worked like a charm but I have noticed suspended threads accumulating and eventually the program stops executing the speech recognizer.  I am sure that I will track this down but any words of wisdom would help.</p>

<p>Sorry for so much detail but I will leave the whole beginners thought process up for those that follow (unless you start to down vote this).</p>

<p>P.S. What an amazing debug environment this is!!!!</p>

<p>It appears that the suspended threads were created while I was debugging, haven't figured out why it did stop working but likely all those suspended threads. I will figure that out.  I have not been able to duplicate that problem and I think I really have have found the answer (above) but I will wait a while before posting this as the answer, just to make sure.</p>

<p>1/21 11:14 EST: Still 2 issues</p>

<p>-About 1 in 10 of voice recognition calls results in an executed onResume() but the run() won't execute after the onResume() (the other 9 times the run() is entered after the onResume()).  This causes my program to hangup as the while loop is not entered.</p>

<p>-Every time a user uses the system's 'Back' arrow to use another program and then returns to my program, another thread (with its own while loop) appears.  Effectively this creates multiple instance of my program and is not acceptable.</p>

<p>AND, I'm back to starting the speech recognizer in a runOnUiThread(), less hangups I think.</p>

<p>1/21 1:27pm EST:</p>

<p>AND AGAIN, I think I have it working.  I have called voice recognition 100 times, have used other programs intermittently and still have the same number of running threads in my debug window and it has not hung up.</p>

<p>What I did was, declare an activity level integer exitloopnow.  I set exitloopnow to 0 in onCreate, onStart and onResume.  I set exitloopnow to 1 in onPause, onStop and onDestroy.  In the run() while loop, I break if exitloopnow==1.</p>

<p>Again, if this continues to work I will set this as the answer unless someone comes up with a better one.</p>

<p>1/21 2:00pm EST:</p>

<p>I guess 100 times was not enough.  I caught it in debug mode at a point where it has hung up.  It appears to be stuck on the .resquestWait() pictured below.</p>

<p>I can't find much on the 'not available [native method]' so again I am stuck.  If I resume code execution and break again, it is always on his line (350).</p>

<p>1/22 9:20am EST:</p>

<p>While the code is hung up at line 350 I can unplug the USB cable and then plug it back in which does create another working thread but that is not desirable.  I can also use the Androids Back button and get another thread by selecting the program in recent apps, this is not desirable either.</p>

<p><img src="http://i.stack.imgur.com/QeJh3.jpg" alt="enter image description here"></p>

<p>Here is the onActivityResult():</p>

<pre><code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == REQUEST_CODE &amp;&amp; resultCode == RESULT_OK)
    {
        // Populate the wordsList with the String values the recognition engine thought it heard
        final ArrayList&lt;String&gt; matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

        this.runOnUiThread(new Runnable() {
            public void run() {
                ((TextView) findViewById(R.id.tvTitle)).setText(matches.get(0));
            }
        });
        BusyV=0;
    }
    super.onActivityResult(requestCode, resultCode, data);
}
</code></pre>

<p>And the current While loop:</p>

<pre><code>@Override
public void run() {
    while (true) {
        request.queue(buffer, 64);
        if (mConnection.requestWait() == request) {
            if (buffer.get(7)==0) {  //New Box (Yellow) button pressed now
                this.runOnUiThread(new Runnable() {
                    public void run() {
                        ((TextView) findViewById(R.id.tvSpine)).setText("Spine");
                        ((TextView) findViewById(R.id.tvPage)).setText("Page");
                        ((TextView) findViewById(R.id.tvThick)).setText("Thick");
                    }
                }); 
                if (CanRecog==1) {
                    if (BusyV!=1) {
                        BusyV=1;

                        this.runOnUiThread(new Runnable() {
                            public void run() {
                                Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                                        RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                                intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recognition ...");
                                startActivityForResult(intent, REQUEST_CODE);       
                            }
                        });
                    }
                }
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
            }
        } else {
            this.runOnUiThread(new Runnable() {
                public void run() {
                    ((TextView) findViewById(R.id.tvZnum)).setText("USB lost at "+ System.currentTimeMillis());
                    ((TextView) findViewById(R.id.tvXnum)).setText("   ");
                }
            });
        }
    }
}
</code></pre>

<p>AND my code for trying to re-establish USB (in the onResume code since onResume is automatically called after the voice recognition onActivityResult():</p>

<pre><code>@Override
public void onResume() {
    super.onResume();
    Intent intent = getIntent();
    Log.d(TAG, "intent: " + intent);
    savetofile("1 intent: " + intent);
    connectToUsb();
}

private void connectToUsb() {
    if (amconnected==1) {
        mConnection.close(); 
        request.close(); 
    } else {            
        setupusb();
    }
    amconnected=0;
    while(amconnected==0) {
        doconnect();
    }   
    request.initialize(mConnection, mEndpointIntr);
}

private void setupusb() {
    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    registerReceiver(mUsbReceiver, filter);
}

private void doconnect() {
    HashMap&lt;String, UsbDevice&gt; deviceList = mUsbManager.getDeviceList();
    Iterator&lt;UsbDevice&gt; deviceIterator = deviceList.values().iterator();
    while (deviceIterator.hasNext()) {
        UsbDevice device1 = deviceIterator.next();
        if (device1.getVendorId() == 1240 &amp; device1.getProductId() == 63) {
            mUsbManager.requestPermission(device1, mPermissionIntent);
            setDevice(device1);
        }
    }
}

private void setDevice(UsbDevice device) {
    Log.d(TAG, "setDevice " + device);
    savetofile("2 setDevice " + device);
    if (device.getInterfaceCount() != 1) {
        Log.e(TAG, "could not find interface");
        savetofile("3 could not find interface");
        return;
    }
    UsbInterface intf = device.getInterface(0);
    UsbEndpoint ep = intf.getEndpoint(0);
    if (ep.getType() != UsbConstants.USB_ENDPOINT_XFER_INT) {
        Log.e(TAG, "endpoint is not interrupt type");
        savetofile("5 endpoint is not interrupt type");
        return;
    }
    mEndpointIntr = ep;
    if (device != null) {
        UsbDeviceConnection connection = mUsbManager.openDevice(device);
        if (connection != null &amp;&amp; connection.claimInterface(intf, true)) {
            Log.d(TAG, "open SUCCESS");
            savetofile("6 open SUCCESS");
            mConnection = connection;
            Thread thread = new Thread(this);
            thread.start();
            amconnected=1;
        } else {
            Log.d(TAG, "open FAIL");
            savetofile("7 open FAIL");
            mConnection = null;
        }
    }
}
</code></pre>

<p>AND my manifest:</p>

<pre><code>&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="act.ProMeasure2D"&gt;

&lt;uses-feature android:name="android.hardware.usb.host" /&gt;
&lt;uses-sdk android:minSdkVersion="13" /&gt;

&lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt;
&lt;uses-permission android:name="android.permission.INTERNET" /&gt;

&lt;application android:theme="@android:style/Theme.Black" android:label="ProMeasure2D"&gt;
    &lt;activity android:name="act.ProMeasure2D.ProMeasure2DActivity"
        android:label="ProMeasure2D"&gt;
        &lt;intent-filter&gt;
            &lt;action android:name="android.intent.action.MAIN" /&gt;
            &lt;category android:name="android.intent.category.DEFAULT" /&gt;
            &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
        &lt;/intent-filter&gt;

        &lt;intent-filter&gt;
            &lt;action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /&gt;
        &lt;/intent-filter&gt;

        &lt;meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
            android:resource="@xml/device_filter" /&gt;
    &lt;/activity&gt;
&lt;/application&gt;
</code></pre>

<p></p>

<p>AND my project structure:
<img src="http://i.stack.imgur.com/CjAH5.jpg" alt="enter image description here"></p>
