1

MainActivityZephyr クラスに測定値を送信する Zephyr HxM デバイスがあります。測定値は正しく受信され、logcat に出力されます。測定値が受信されると、メソッド測定で分析され、editText は受信したすべての測定値で継続的に変化し続けるはずです。

アクティビティが HxM デバイスに接続するとすぐに、アクティビティは完全にフリーズし、editText は変更されませんが、受信した値はログ cat に正常に出力され、コードは正常に実行され、条件が満たされると、ユーザーは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;
} 
4

2 に答える 2

0

ボタンのクリック時に、メイン UI スレッドですべての重いタスクを実行しています。ボタンをクリックするとアクティビティがフリーズするのはそのためです。AsyncTaskなどの重いタスクはバックグラウンド スレッドで実行する必要があります。

于 2013-05-27T11:45:22.330 に答える
0

わかりませんが、あなたが説明しているのは、おそらく、すべての重い作業を別のスレッドで実行していないため、作業が行われている間にANRが発生し、作業が終了するとUIが応答するということです.

AsyncTask、スレッド、ハンドラーについて読んでください。 AsyncTask またはサービスから UI コンポーネントに通知するベスト プラクティス

于 2013-05-27T11:48:38.560 に答える