Activity freezes when button is clicked but code runs in background
<p>I have a Zephyr HxM device which sends measurements to the MainActivityZephyr class, the measurements are received correctly and are printed in the logcat. When the measurement is received, it's supposed to be analyzed in the method measurement and the editText is supposed to continuously keep changing with the value of every measurement received.</p>

<p>What happens is as soon as the activity connects with the HxM device, it freezes completely and the  editText does not change but the values received are printed normally in the log cat and the code is executed normally and when the condition is fulfilled, the user is transferred to the RedAlert activity normally. </p>

<p>Any help as to why this is happening and how can I fix it would be greatly appreciated! Thanks in advance.</p>

<p>Below is the MainActivityZephyr class (I removed some of the methods of the locationlistener for shortening purposes):</p>

<pre><code>public class MainActivityZephyr extends Activity implements LocationListener{
    /** Called when the activity is first created. */
    BluetoothAdapter adapter = null;
    BTClient _bt;
    ZephyrProtocol _protocol;
    NewConnectedListener _NConnListener;
    private final int HEART_RATE = 0x100;
    private final int INSTANT_SPEED = 0x101;
    MediaPlayer mp;
    EditText meas;
    String m;
    Button back;
    String r[] ;
    String y[] ;
 Runnable Refresh;

    String hour1;
    int pm_am;
    int min;
    int sec;
    int hour;   
    Button a;

    TextView measure;

    String month;
    String dayOfweek;
    String amPm;

    String date;

    int methodTimeHour;
    int methodTimeMin;


    static ArrayList&lt;GeoPoint&gt; points =new ArrayList&lt;GeoPoint&gt;();

    private LocationManager locManager;

    static String HeartRatetext;
     final Handler handler = new Handler();
    @Override
    public void onCreate(Bundle savedInstanceState) {
         unmute();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        /*Sending a message to android that we are going to initiate a pairing request*/
        IntentFilter filter = new IntentFilter("android.bluetooth.device.action.PAIRING_REQUEST");
        /*Registering a new BTBroadcast receiver from the Main Activity context with pairing request event*/
       this.getApplicationContext().registerReceiver(new BTBroadcastReceiver(), filter);
        // Registering the BTBondReceiver in the application that the status of the receiver has changed to Paired
        IntentFilter filter2 = new IntentFilter("android.bluetooth.device.action.BOND_STATE_CHANGED");
       this.getApplicationContext().registerReceiver(new BTBondReceiver(), filter2);

      //Obtaining the handle to act on the CONNECT button
        TextView tv = (TextView) findViewById(R.id.labelStatusMsg);
        String ErrorText  = "Not Connected to HxM ! !";
         tv.setText(ErrorText);
         a = (Button) findViewById(R.id.button1);
            a.setVisibility(View.GONE);



            locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
                    0, this);


        Button btnConnect = (Button) findViewById(R.id.ButtonConnect);
        if (btnConnect != null)
        {
            btnConnect.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    String BhMacID = "00:07:80:9D:8A:E8";
                    //String BhMacID = "00:07:80:88:F6:BF";
                    adapter = BluetoothAdapter.getDefaultAdapter();

                    Set&lt;BluetoothDevice&gt; pairedDevices = adapter.getBondedDevices();

                    if (pairedDevices.size() &gt; 0) 
                    {
                        for (BluetoothDevice device : pairedDevices) 
                        {
                            if (device.getName().startsWith("HXM")) 
                            {
                                BluetoothDevice btDevice = device;
                                BhMacID = btDevice.getAddress();
                                break;

                            }
                        }


                    }

                    //BhMacID = btDevice.getAddress();
                    BluetoothDevice Device = adapter.getRemoteDevice(BhMacID);
                    String DeviceName = Device.getName();
                    _bt = new BTClient(adapter, BhMacID);
            _NConnListener = new NewConnectedListener(Newhandler,Newhandler);


                    _bt.addConnectedEventListener(_NConnListener);

                    TextView tv1 = (EditText)findViewById(R.id.labelHeartRate);
                    tv1.setText("000");

                     tv1 = (EditText)findViewById(R.id.labelInstantSpeed);
                     tv1.setText("0.0");


                    if(_bt.IsConnected())
                    {
                        _bt.start();
                        TextView tv = (TextView) findViewById(R.id.labelStatusMsg);
                        String ErrorText  = "Connected to HxM "+DeviceName;
                         tv.setText(ErrorText);

                         //Reset all the values to 0s

                    }
                    else
                    {
                        TextView tv = (TextView) findViewById(R.id.labelStatusMsg);
                        String ErrorText  = "Unable to Connect !";
                         tv.setText(ErrorText);
                    }
                }
            });
        }
        /*Obtaining the handle to act on the DISCONNECT button*/
        Button btnDisconnect = (Button) findViewById(R.id.ButtonDisconnect);
        if (btnDisconnect != null)
        {
            btnDisconnect.setOnClickListener(new OnClickListener() {
                @Override
                /*Functionality to act if the button DISCONNECT is touched*/
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    /*Reset the global variables*/
                    TextView tv = (TextView) findViewById(R.id.labelStatusMsg);
                    String ErrorText  = "Disconnected from HxM!";
                     tv.setText(ErrorText);

                    /*This disconnects listener from acting on received messages*/  
                    _bt.removeConnectedEventListener(_NConnListener);
                    /*Close the communication with the device &amp; throw an exception if failure*/
                    _bt.Close();

                }
            });
        }
    }
    private class BTBondReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle b = intent.getExtras();
            BluetoothDevice device = adapter.getRemoteDevice(b.get("android.bluetooth.device.extra.DEVICE").toString());
            Log.d("Bond state", "BOND_STATED = " + device.getBondState());
        }
    }
    private class BTBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("BTIntent", intent.getAction());
            Bundle b = intent.getExtras();
            Log.d("BTIntent", b.get("android.bluetooth.device.extra.DEVICE").toString());
            Log.d("BTIntent", b.get("android.bluetooth.device.extra.PAIRING_VARIANT").toString());
            try {
                BluetoothDevice device = adapter.getRemoteDevice(b.get("android.bluetooth.device.extra.DEVICE").toString());
                Method m = BluetoothDevice.class.getMethod("convertPinToBytes", new Class[] {String.class} );
                byte[] pin = (byte[])m.invoke(device, "1234");
                m = device.getClass().getMethod("setPin", new Class [] {pin.getClass()});
                Object result = m.invoke(device, pin);
                Log.d("BTTest", result.toString());
            } catch (SecurityException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (NoSuchMethodException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }



    final  Handler Newhandler = new Handler(){
        public void handleMessage(Message msg)
        {

            EditText tv2;
            EditText tv3;
            switch (msg.what)
            {
            case HEART_RATE:
                HeartRatetext = msg.getData().getString("HeartRate");
                tv2 = (EditText)findViewById(R.id.labelHeartRate);
                System.out.println("Heart Rate Info is "+ HeartRatetext);
                //if (tv != null)
                    //{
                    tv2.setText(HeartRatetext);

                    //Refresh = new Runnable() {
                        //public void run() {


                            //handler.postDelayed(Refresh, 1000*100);
                measurement(HeartRatetext, methodTimeHour,methodTimeMin);
                        //}
                        //};
                        //handler.post(Refresh);






                    //}

            break;

            case INSTANT_SPEED:
                String InstantSpeedtext = msg.getData().getString("InstantSpeed");
                tv3 = (EditText)findViewById(R.id.labelInstantSpeed);
                if (tv3 != null)tv3.setText(InstantSpeedtext);

            break;

            }
    }

    };




  public void measurement(String mn, int methodHour, int methodMin){

      r=UserFunctions.red.replace("[", "").replace("\"", "").replace("]", "").split("to");
      y=UserFunctions.yell.replace("[", "").replace("\"", "").replace("]", "").split("to");

      Calendar c = Calendar.getInstance(); 
        /*hour1 = c.get(Calendar.HOUR)+"";
        pm_am = c.get(Calendar.AM_PM);*/

       hour = c.get(Calendar.HOUR);
        min = c.get(Calendar.MINUTE);
        sec = c.get(Calendar.SECOND);

    //  if ((methodHour ==0 &amp;&amp; methodMin==0)  || (methodMin- min&gt; 2)){
            // Do something[
            if(!(mn.equals("000"))){

            UserFunctions userFunction = new UserFunctions();
           Log.d("foneeeeeeeeeeeeeeeee",userFunction.GetFoneNo(userFunction.drID).toString());

            String no =userFunction.fone1;

          String no1 =userFunction.fone2;
            //String m=meas.getText().toString();
            //int mm= Integer.parseInt(m);
            int mm=Integer.parseInt(mn);

            switch(pm_am){
                case 0: amPm = "AM";
                case 1: amPm = "PM";

                }
            if(mm&gt;Integer.parseInt(r[0])&amp;&amp;mm&lt;Integer.parseInt(r[1])){
                //Newhandler.sendEmptyMessageDelayed(0,0000);


                _bt.removeConnectedEventListener(_NConnListener);
                _bt.Close();
                Newhandler.removeCallbacks(Refresh);

                Intent dashboard = new Intent(getApplicationContext(), RedAlert.class);
                // Close all views before launching Dashboard
                dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(dashboard);
                // Close Registration Screen
                finish();

            }


                 if(isOnline()){


                 userFunction.meas(mn,userFunction.drID,date,amPm); 
                 }
                 else{
                     ///store in mobiles database

                 }

            }
    //    }

  }

}
</code></pre>

<p>the isOnline() method:</p>

<pre><code>public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null &amp;&amp; netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
} 
</code></pre>
