2013-05-27 27 views
1

我有一臺Zephyr HxM設備,它將測量值發送到MainActivityZephyr類,測量值正確接收並打印在logcat中。當接收到測量值時,應該在方法測量中進行分析,並且editText應該不斷隨着接收到的每個測量值而變化。單擊按鈕但代碼在後臺運行時活動會凍結

當活動與HxM設備連接後,它會完全凍結並且editText不會更改,但收到的值通常會打印在日誌文件中,並且代碼正常執行並且條件滿足時,用戶通常會轉到RedAlert活動。

任何幫助,爲什麼發生這種情況,我如何解決它將不勝感激!提前致謝。

下面是MainActivityZephyr類(我刪除了一些LocationListener的方法縮短目的):

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<GeoPoint> points =new ArrayList<GeoPoint>(); 

    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<BluetoothDevice> pairedDevices = adapter.getBondedDevices(); 

        if (pairedDevices.size() > 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 & 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 && methodMin==0) || (methodMin- min> 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>Integer.parseInt(r[0])&&mm<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 

       } 

      } 
    // } 

    } 

} 

的isOnline()方法:

public boolean isOnline() { 
    ConnectivityManager cm = 
     (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
    if (netInfo != null && netInfo.isConnectedOrConnecting()) { 
     return true; 
    } 
    return false; 
} 
+0

「背景」是什麼意思? – Blackbelt

+0

我只是說它運行正常。 – Salma

回答

0

你正在做的所有的重點擊按鈕時,主UI線程中的任務。這是您的活動凍結點擊按鈕的原因。 您應該在後臺線程中執行繁重的任務,如AsyncTask

+0

我試圖做到這一點,但我似乎無法把isOnline方法放在asyncTask類中,是否有無論如何這樣做? – Salma

+0

有什麼問題? – bakriOnFire

+0

我試着把度量()方法放在AsyncTask中,但它沒有起作用,你建議我在AsyncTask中放入什麼部分? – Salma