Вылетает приложение при выходе в главное меню

Всем привет, разрабатываю многооконное приложение на андроид и столкнулся с проблемой при переключении между активити, 2 активити переключаются нормально и выходят в меню, а третье вылетает при выходе в меню(Ручное управление),

package com.example.upravlenie_servo;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

public class Manual_Control extends Activity
{
    private static final String TAG = "bluetooth1";
    String answer;
    Button menu;
    ImageButton left, right, up, down, rotate_left, rotate_right, szgat, raszgat,left2, right2;
    Handler h;
    private static final int REQUEST_ENABLE_BT = 1;
    final int RECIEVE_MESSAGE = 1;        // Статус для Handler
    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    private StringBuilder sb = new StringBuilder();


    private Manual_Control.ConnectedThread mConnectedThread;
    // SPP UUID сервиса
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    // MAC-адрес Bluetooth модуля
    private static String address = "FC:A8:9A:00:2A:07";  //Вместо “00:00” Нужно нудет ввести MAC нашего bluetooth
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.manual_control);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // или горизонтальная
        left=(ImageButton)findViewById(R.id.left);
        right=(ImageButton)findViewById(R.id.right);
        up=(ImageButton)findViewById(R.id.up);
        down=(ImageButton)findViewById(R.id.down);
        rotate_left=(ImageButton)findViewById(R.id.rotate_left);
        rotate_right=(ImageButton)findViewById(R.id.rotate_right);
        szgat=(ImageButton)findViewById(R.id.szgat);
        raszgat=(ImageButton)findViewById(R.id.raszgat);
        left2=(ImageButton)findViewById(R.id.left2);
        right2=(ImageButton)findViewById(R.id.right2);
        menu= (Button) findViewById(R.id.menu);


        h = new Handler() {
            public void handleMessage(android.os.Message msg) {
                switch (msg.what) {
                    case RECIEVE_MESSAGE:                                                   // если приняли сообщение в Handler
                        byte[] readBuf = (byte[]) msg.obj;
                        String strIncom = new String(readBuf, 0, msg.arg1);
                        sb.append(strIncom);                                                // формируем строку
                        int endOfLineIndex = sb.indexOf("\r\n");                            // определяем символы конца строки
                        if (endOfLineIndex > 0) {                                            // если встречаем конец строки,
                            String sbprint = sb.substring(0, endOfLineIndex);               // то извлекаем строку
                            sb.delete(0, sb.length());                                      // и очищаем sb
                            answer=sbprint;
                            if(answer.equals("OK")){}
                            else
                            {
                                Toast.makeText(getBaseContext(), "Обрыв связи", Toast.LENGTH_SHORT).show();
                            }
                            Toast.makeText(getBaseContext(), "Ответ от Arduino: " + answer, Toast.LENGTH_SHORT).show();  //выводим на устройстве сообщение
                            //txtArduino.setText("Ответ от Arduino: " + sbprint);             // обновляем TextView
                            left.setEnabled(true);
                            right.setEnabled(true);
                            up.setEnabled(true);
                            down.setEnabled(true);
                            rotate_left.setEnabled(true);
                            rotate_right.setEnabled(true);
                            szgat.setEnabled(true);
                            raszgat.setEnabled(true);
                            left2.setEnabled(true);
                            right2.setEnabled(true);
                        }
                        //Log.d(TAG, "...Строка:"+ sb.toString() +  "Байт:" + msg.arg1 + "...");
                        break;
                }
            };
        };
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        checkBTState();
        left.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mConnectedThread.write("ATML\r\n");
                        return true; // if you want to handle the touch event
                    case MotionEvent.ACTION_UP:
                        mConnectedThread.write("1");
                        return true; // if you want to handle the touch event
                }
                return false;
            }
        });
        right.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mConnectedThread.write("ATMR\r\n");
                        return true; // if you want to handle the touch event
                    case MotionEvent.ACTION_UP:
                        mConnectedThread.write("1");
                        return true; // if you want to handle the touch event
                }
                return false;
            }
        });
        up.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mConnectedThread.write("ATMU\r\n");
                        return true; // if you want to handle the touch event
                    case MotionEvent.ACTION_UP:
                        mConnectedThread.write("1");
                        return true; // if you want to handle the touch event
                }
                return false;
            }
        });
        down.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mConnectedThread.write("ATMD\r\n");
                        return true; // if you want to handle the touch event
                    case MotionEvent.ACTION_UP:
                        mConnectedThread.write("1");
                        return true; // if you want to handle the touch event
                }
                return false;
            }
        });
        rotate_left.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mConnectedThread.write("ATMB1\r\n");
                        return true; // if you want to handle the touch event
                    case MotionEvent.ACTION_UP:
                        mConnectedThread.write("1");
                        return true; // if you want to handle the touch event
                }
                return false;
            }
        });
        rotate_right.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mConnectedThread.write("ATMB2\r\n");
                        return true; // if you want to handle the touch event
                    case MotionEvent.ACTION_UP:
                        mConnectedThread.write("1");
                        return true; // if you want to handle the touch event
                }
                return false;
            }
        });
        szgat.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mConnectedThread.write("ATMF1\r\n");
                        return true; // if you want to handle the touch event
                    case MotionEvent.ACTION_UP:
                        mConnectedThread.write("1");
                        return true; // if you want to handle the touch event
                }
                return false;
            }
        });
        raszgat.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mConnectedThread.write("ATMF2\r\n");
                        return true; // if you want to handle the touch event
                    case MotionEvent.ACTION_UP:
                        mConnectedThread.write("1");
                        return true; // if you want to handle the touch event
                }
                return false;
            }
        });
        left2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mConnectedThread.write("ATMS2\r\n");
                        return true; // if you want to handle the touch event
                    case MotionEvent.ACTION_UP:
                        mConnectedThread.write("1");
                        return true; // if you want to handle the touch event
                }
                return false;
            }
        });
        right2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mConnectedThread.write("ATMS1\r\n");
                        return true; // if you want to handle the touch event
                    case MotionEvent.ACTION_UP:
                        mConnectedThread.write("1");
                        return true; // if you want to handle the touch event
                }
                return false;
            }
        });
    }
    public void onButtonClick(View v)
    {
        if(v.getId()==R.id.menu)
        {
            finish();
        }
    }
    @Override
    public void onResume() {
        super.onResume();

        Log.d(TAG, "...onResume - попытка соединения...");

        // Set up a pointer to the remote node using it's address.
        BluetoothDevice device = btAdapter.getRemoteDevice(address);

        // Two things are needed to make a connection:
        //   A MAC address, which we got above.
        //   A Service ID or UUID.  In this case we are using the
        //     UUID for SPP.
        try {
            btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
        }

        // Discovery is resource intensive.  Make sure it isn't going on
        // when you attempt to connect and pass your message.
        btAdapter.cancelDiscovery();

        // Establish the connection.  This will block until it connects.
        Log.d(TAG, "...Соединяемся...");
        try {
            btSocket.connect();
            Log.d(TAG, "...Соединение установлено и готово к передачи данных...");
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {
                errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
            }
        }

        // Create a data stream so we can talk to server.
        Log.d(TAG, "...Создание Socket...");
        mConnectedThread = new Manual_Control.ConnectedThread(btSocket);
        mConnectedThread.start();
    }

    @Override
    public void onPause() {
        super.onPause();

        Log.d(TAG, "...In onPause()...");

        try     {
            btSocket.close();
        } catch (IOException e2) {
            errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
        }
    }

    private void checkBTState() {
        // Check for Bluetooth support and then check to make sure it is turned on
        // Emulator doesn't support Bluetooth and will return null
        if(btAdapter==null) {
            errorExit("Fatal Error", "Bluetooth не поддерживается");
        } else {
            if (btAdapter.isEnabled()) {
                Log.d(TAG, "...Bluetooth включен...");
            } else {
                //Prompt user to turn on Bluetooth
                Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }
    }

    private void errorExit(String title, String message){
        Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
        finish();
    }

    static class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        private Handler h;
        private int RECIEVE_MESSAGE;

        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer = new byte[256];  // buffer store for the stream
            int bytes; // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);        // Получаем кол-во байт и само собщение в байтовый массив "buffer"
                    h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Отправляем в очередь сообщений Handler
                } catch (IOException e) {
                    break;
                }
            }
        }

        /* Call this from the main activity to send data to the remote device */
        public void write(String message) {
            Log.d(TAG, "...Данные для отправки: " + message + "...");
            byte[] msgBuffer = message.getBytes();
            try {
                mmOutStream.write(msgBuffer);
            } catch (IOException e) {
                Log.d(TAG, "...Ошибка отправки данных: " + e.getMessage() + "...");
            }
        }

        /* Call this from the main activity to shutdown the connection */
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }
}

Ответы (0 шт):