传感器线程和处理程序线程问题

时间:2016-11-03 13:51:10

标签: android multithreading handler android-sensors chronometer

我正在为Sony Smarthwatch 3开发应用程序。

它在来自蓝牙连接的其他设备的命令后记录音频和传感器值。 我试着更清楚。

问题

  1. Handler不会更新关联的TextView(也Button未正确设置)。处理程序附加到" log" TextView只是在执行结束时用最后发送的文本更新视图。
  2. 传感器不会根据需要更新字段。传感器和相关的听众被正确地实例化,但我不能保存与他们正在考虑的事件相关的值。我应该保存值的字符串永远不会改变,它就像听众永远不会找到相关的事件。我已经在此设备上测试了传感器并且它们正常工作。
  3. 计时器不起作用。无所谓开始他的计数。它并不重要,但我想明白为什么。我正在思考与线程相关的一些问题,但我不知道如何管理它。
  4. 主要代码

    public class MainActivity extends Activity implements OnRequestPermissionsResultCallback{
    
        //GUI Elements
        Chronometer chrono;
        TextView log;
        Button button;
        MyHandlerThread update;
        Handler myHandler;
        boolean ready;
    
        //Bluetooth Connection
        BluetoothAdapter adapter;
        BluetoothServerSocket serverSocket;
        BluetoothDevice clientDevice;
        BluetoothSocket clientSocket;
        final UUID id = UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00");
        InputStream in;
    
        /*Sensors*/
        SensorManager manager;
        Sensor acc, gyr, mag;
        SensorEventListener accEvent, gyrEvent, magEvent;
    
        /*Microphone*/
        MediaRecorder medRec;
    
        /*File Data*/
        File data;
        FileWriter writer;
        long time;
        Thread writing;
        String accValues="", gyrValues="", magValues="";
    
    
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
    
            stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
                @Override
                public void onLayoutInflated(WatchViewStub stub) {
    
    
                    //GUI Elements
                    chrono = (Chronometer)findViewById(R.id.chrono);
                    log = (TextView) findViewById(R.id.logger);
                    button = (Button) findViewById(R.id.start);
                    myHandler= new MyHandler();
                    update = new MyHandlerThread(myHandler);
                    update.start();
    
    
                    ready=true;
                    writing=null;
    
                    //Listner
                    button.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
    
                            //flag di stato
                            //boolean ready = (button.getText().equals("Start"));
                            audioInit();            //Audio Init, defined below
                            fileInit();             //File Init, defined below
    
                            if(ready){                                              
                                try {
                                    bluetoothInit();                      //Bluetooth Init, defined below
                                } catch (Exception e) {/**/}
    
                                if (!adapter.isEnabled()){                          
                                    update.setMessage("please, Turn Bluetooth On");
                                }
                                else{   
                                    try {
                                        update.setMessage("Waiting Device...");
                                        bluetoothConnect();
                                        if(clientSocket!=null && in != null) {
                                            update.setMessage("Connected:\n"+ clientDevice.getName());
                                        }
                                        while(ready){
                                            int cmd = in.read();        //1 = start, 0 = stop
                                            if(cmd == 1){
                                                update.setMessage("Should be Ready");
                                                time=SystemClock.elapsedRealtime();
                                                update.setMessage("Recording...");
                                                button.setText("Stop");
                                                try {
                                                    if(writing==null)
                                                    writing = new Thread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            while(ready){
                                                                try {
                                                                    stopSensor();       //Defined Below
                                                                    writer.flush();     //Clear Stream
                                                                    writer.append((SystemClock.elapsedRealtime()-time)+";");    //Writing Record in CSV
                                                                    writer.append(accValues+gyrValues+magValues+"\n");
                                                                    sensorInit();       //Sensor Init, defined Below
                                                                    wait(250);
                                                                } catch (Exception e) {
                                                                    e.printStackTrace();
                                                                }
                                                            }
                                                        }
                                                    });
                                                    sensorInit();
                                                    writing.start();    //Start Thread Reading/Writing for Sensor values
                                                    startRecord();      //Audio and Chrono Start
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                            else if (cmd==0){
                                                //log.setText("Should be Stopped");
                                                update.setMessage("Should be Stopped");
                                                ready=false;
                                                writing=null;
                                                stopRecord();
                                                update.setMessage("Stopped");
                                                button.setText("Start");
                                            }
                                        }
                                    } catch (Exception e) {
                                        //log.setText("Bluetooth Problem");
                                        update.setMessage("Bluetooth Problem");
                                    }
                                }
                            }
                        }
                    }); //fine Listner
    
    
    
                }
            });
        }
    
        /*Handler for Log TextView*/
        private class MyHandler extends Handler {
            public MyHandler(){
                super(Looper.getMainLooper());
            }
    
            public void handleMessage(Message msg) {
                Bundle bundle = msg.getData();
                if(bundle.containsKey("refresh")) {
                    String value = bundle.getString("refresh");
                    log.setText(value);
                }
            }
        }
    
        /*Bluetooth Init*/
        void bluetoothInit(){
            try {
                adapter = BluetoothAdapter.getDefaultAdapter();
                serverSocket = adapter.listenUsingRfcommWithServiceRecord("TennisRecord",id);
                clientSocket=null;
                clientDevice=null;
                in=null;
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /*Bluetooth Connection*/
        void bluetoothConnect() throws IOException {
            clientSocket = serverSocket.accept();
            clientDevice = clientSocket.getRemoteDevice();
            in=clientSocket.getInputStream();
        }
    
        /*Audio Init*/
        void audioInit(){
    
            medRec = new MediaRecorder();
            medRec.setAudioSource(MediaRecorder.AudioSource.MIC);
            medRec.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            medRec.setOutputFile(Environment.getExternalStorageDirectory()+"/tennis_record.3gp");
            medRec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            medRec.setAudioSamplingRate(44100);
            medRec.setAudioChannels(1);
        }
    
        /*File Init*/
        void fileInit(){
            try {
                data=new File(Environment.getExternalStorageDirectory(),"/data.csv");
                writer = new FileWriter(data);
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    
        /*Sensors Init*/
        void sensorInit(){
            manager = (SensorManager) getSystemService(SENSOR_SERVICE);
            acc = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            gyr = manager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
            mag = manager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    
            accEvent = new SensorEventListener() {
                @Override
                public void onSensorChanged(SensorEvent event) {
                    accValues=event.values[0]+";"+event.values[1]+";"+event.values[2]+";";
                    log.setText((int) event.values[0]);
                }
    
                @Override
                public void onAccuracyChanged(Sensor sensor, int accuracy) {
    
                }
            };
            gyrEvent = new SensorEventListener() {
                @Override
                public void onSensorChanged(SensorEvent event) {
                    gyrValues=event.values[0]+";"+event.values[1]+";"+event.values[2]+";";
    
                }
    
                @Override
                public void onAccuracyChanged(Sensor sensor, int accuracy) {
    
                }
            };
            magEvent = new SensorEventListener() {
                @Override
                public void onSensorChanged(SensorEvent event) {
                    magValues=event.values[0]+";"+event.values[1]+";"+event.values[2]+";";
    
                }
    
                @Override
                public void onAccuracyChanged(Sensor sensor, int accuracy) {
    
                }
            };
    
            manager.registerListener(accEvent,acc,SensorManager.SENSOR_DELAY_NORMAL);
            manager.registerListener(gyrEvent,gyr,SensorManager.SENSOR_DELAY_NORMAL);
            manager.registerListener(magEvent,mag,SensorManager.SENSOR_DELAY_NORMAL);
    
        }
    
        /*Start Records*/
        void startRecord() throws IOException {
            /*Microfono*/
            medRec.prepare();
            medRec.start();
            /*Cronometro*/
            chrono.setBase(SystemClock.elapsedRealtime());
            chrono.start();
        }
    
        /*Close Record*/
        void stopRecord(){
            /*Microfono*/
            medRec.stop();
            medRec.release();
            medRec=null;
            /*Cronometro*/
            chrono.setBase(SystemClock.elapsedRealtime());
            chrono.stop();
    
            /*File*/
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        /*Stop Senors*/
        void stopSensor(){
            /*Sensori*/
            manager.unregisterListener(accEvent);
            manager.unregisterListener(gyrEvent);
            manager.unregisterListener(magEvent);
        }
    }
    

    另一个类中的Handler线程

    public class MyHandlerThread extends Thread {
        private Handler handler;
        Queue<String> text;
        public MyHandlerThread(Handler handler) {
            this.handler = handler;
            text=new ArrayDeque<String>();
    
        }
        public void run() {
            try {
                while(true) {
                    if(!text.isEmpty()){
                        notifyMessage(text.remove());
                        Thread.sleep(1000);
                    }
                }
            }catch(Exception ex) {}
        }
    
        public void setMessage(String str){
            text.add(str);
        }
    
        private void notifyMessage(String str) {
            Message msg = handler.obtainMessage();
            Bundle b = new Bundle();
            b.putString("refresh", ""+str);
            msg.setData(b);
            handler.sendMessage(msg);
        }
    }
    

    任何解决方案?

0 个答案:

没有答案