Java 如何启动BluetoothHandler的另一(多)项活动?

Java 如何启动BluetoothHandler的另一(多)项活动?,java,android,obd-ii,Java,Android,Obd Ii,我正在制作一个OBDII蓝牙Android应用程序,在发送命令时遇到了一些问题。我已经成功地在我的移动设备和OBDII适配器之间建立了连接,但是当我单击另一个活动时,蓝牙连接似乎退出了 当你打开应用程序时,你会看到一个按钮,上面写着“连接设备”。当您按下该键时,一个ListAdapter将与配对的蓝牙设备一起显示。然后,当您成功连接到设备(OBDII适配器)时,它会将您带到另一个布局,其中有3个活动是3个不同的汽车动力平台。这就是问题所在。现在,我只想能够读取OBDII的电压。但是当我在3个活动

我正在制作一个OBDII蓝牙Android应用程序,在发送命令时遇到了一些问题。我已经成功地在我的移动设备和OBDII适配器之间建立了连接,但是当我单击另一个活动时,蓝牙连接似乎退出了

当你打开应用程序时,你会看到一个按钮,上面写着“连接设备”。当您按下该键时,一个ListAdapter将与配对的蓝牙设备一起显示。然后,当您成功连接到设备(OBDII适配器)时,它会将您带到另一个布局,其中有3个活动是3个不同的汽车动力平台。这就是问题所在。现在,我只想能够读取OBDII的电压。但是当我在3个活动中的一个内单击我的按钮getValue时。我得到一个logcat错误。我想这是因为我没有正确地启动我的BluetoothHandler。我不知道怎么做

main活动:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button b1;
    BluetoothAdapter mAdapter;
    FragmentHostCallback mHost;
    BTHandler btHandler;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case BTHandler.STATE_CONNECTED:
                            //setContentView(R.layout.activity_connected);
                            Intent intent = new Intent(MainActivity.this, Connected.class);
                            startActivity(intent);
                            Toast.makeText(getApplicationContext(), R.string.title_connected_to, Toast.LENGTH_SHORT).show();
                            Log.v("Log", "Connected");
                            break;
                        case BTHandler.STATE_NONE:
                            Toast.makeText(getApplicationContext(), R.string.title_not_connected, Toast.LENGTH_SHORT).show();
                            break;
                    }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btHandler = new BTHandler(MainActivity.this, mHandler);
        b1 = (Button) findViewById(R.id.connect);
        b1.setOnClickListener(this);
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        //init();

        if (mAdapter == null) {
            Toast.makeText(getApplicationContext(), R.string.device_not_supported, Toast.LENGTH_LONG).show();
            finish();
        } else {
            if (!mAdapter.isEnabled()) {
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(intent, 1);
            }
        }
        //BTHandler btHandler = new BTHandler(MainActivity.this, mHandler);
        //btHandler.connect("");
    }

    public void onClick(View v) {
        int id = v.getId();
        //String voltage = ("ATRV");

        switch (id) {
            case R.id.connect:
                onConnect(); //Operation
                Log.v("Log", "Pressed onClick");
                break;
            /*case R.id.getValue:
                btHandler.write(voltage);
                Log.v("Log", "getValue" + voltage);
                break;*/
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), R.string.enable_bluetooth, Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void onConnect() {
        ArrayList deviceStrs = new ArrayList();
        final ArrayList<String> devices = new ArrayList();

        BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
        Set pairedDevices = mAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (Object device : pairedDevices) {
                BluetoothDevice bdevice = (BluetoothDevice) device;
                deviceStrs.add(bdevice.getName() + "\n" + bdevice.getAddress());
                devices.add(bdevice.getAddress());
            }
        }

        // show list
        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.select_dialog_singlechoice,
                deviceStrs.toArray(new String[deviceStrs.size()]));

        alertDialog.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                int position = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                String deviceAddress = devices.get(position);

                btHandler.connect(deviceAddress);
                //btHandler.write();

            }
        });
        alertDialog.setTitle("Paired devices");
        alertDialog.show();
    }
public class BTHandler {

    public static final int STATE_NONE = 0;       // we're doing nothing
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
    public static final int STATE_CONNECTED = 3;  // now connected to a remote device

    final ArrayList<String> devices = new ArrayList();
    private final Handler mHandler;
    private BluetoothAdapter mAdapter;
    private BluetoothDevice device;
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    private BluetoothSocket socket;
    private String status;
    private int mState;
    private boolean connectionStatus = false;

    public BTHandler(Context context, Handler handler) { // Konstruktor
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        mHandler = handler;
    }

    public void write(String s) {
        mConnectedThread.sendRawCommand(s);
        Log.v("write", "write");
    }

    /*
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) {
        }
    }
    */
    public void connect(String deviceAddress) {
        mConnectThread = new ConnectThread(deviceAddress);
        mConnectThread.start();
    }

    private void guiHandler(int what, int arg1, String obj) {
        Message msg = mHandler.obtainMessage();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.sendToTarget();
    }

    private class ConnectThread extends Thread {
        BluetoothSocket tmp = null;
        private BluetoothSocket mmSocket;

        public ConnectThread(String deviceAddress) {
            mAdapter = BluetoothAdapter.getDefaultAdapter();
            device = mAdapter.getRemoteDevice(deviceAddress);

            BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
            BluetoothDevice device = mAdapter.getRemoteDevice(deviceAddress);
            UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
            try {
                tmp = device.createRfcommSocketToServiceRecord(uuid);
                //socket.connect();
                //Log.v("connect", "connect");
            } catch (IOException e) {
                //e.printStackTrace();
                //Log.v("exception", "e");
            }
            mmSocket = tmp;
        }

        public void run() {
            // Cancel discovery because it will slow down the connection
            mAdapter.cancelDiscovery();
            byte[] buffer = new byte[1024]; // buffer store for the stream
            int bytes;

            try {
                // Connect the device through the socket. This will block
                // until it succeeds or throws an exception
                mmSocket.connect();
                Log.v("connect", "connect");
            } catch (IOException connectException) {
                // Unable to connect; close the socket and get out
                try {
                    mmSocket.close();
                    Log.v("close", "close");
                } catch (IOException closeException) {
                }
                guiHandler(Constants.TOAST, Constants.SHORT, "Connection Failed");
                return;
            }
            guiHandler(Constants.CONNECTION_STATUS, Constants.STATE_CONNECTED, "");
            mConnectedThread = new ConnectedThread(mmSocket);
            mConnectedThread.start();
        }
    }

    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        private ObdMultiCommand multiCommand;

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

            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;

            try {
                //RPMCommand engineRpmCommand = new RPMCommand();
                //SpeedCommand speedCommand = new SpeedCommand();
                ModuleVoltageCommand voltageCommand = new ModuleVoltageCommand();

                while (!Thread.currentThread().isInterrupted()) {
                    //engineRpmCommand.run(mmInStream, mmOutStream); //(socket.getInputStream(), socket.getOutputStream());
                    //speedCommand.run(mmInStream, mmOutStream); //(socket.getInputStream(), socket.getOutputStream());
                    voltageCommand.run(socket.getInputStream(), socket.getOutputStream());
                    // TODO handle commands result
                    //Log.d("Log", "RPM: " + engineRpmCommand.getFormattedResult());
                    //Log.d("Log", "Speed: " + speedCommand.getFormattedResult());
                    Log.v("Log", "Voltage: " + voltageCommand.getFormattedResult());
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

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

            OBDcmds();
            // Keep listening to the InputStream until an exception occurs
            while (connectionStatus) {
                sendMultiCommand();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        // CALL this to MainActivity
        public void sendRawCommand(String command) {
            try {
                new OdbRawCommand(command);

            } catch (Exception e) {
                Log.v("sendRawCommand", "e");
            }
        }

        private void OBDcmds() { // execute commands

            try {
                new EchoOffCommand().run(socket.getInputStream(), socket.getOutputStream());
                new LineFeedOffCommand().run(socket.getInputStream(), socket.getOutputStream());
                new TimeoutCommand(100).run(socket.getInputStream(), socket.getOutputStream());
                new SelectProtocolCommand(ObdProtocols.AUTO).run(socket.getInputStream(), socket.getOutputStream()); //ISO_15765_4_CAN

            } catch (Exception e) {
                Log.v("OBDcmds", "e");
                // handle errors
            }
        }
        /*
        // Call this from the main activity to send data to the remote device
        public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) {
            }
        }
        */

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

        public void sendMultiCommand() {
            try {
                // RUN some code here
            } catch (Exception e) {
            }
        }
    }
}
Logcat:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button b1;
    BluetoothAdapter mAdapter;
    FragmentHostCallback mHost;
    BTHandler btHandler;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case BTHandler.STATE_CONNECTED:
                            //setContentView(R.layout.activity_connected);
                            Intent intent = new Intent(MainActivity.this, Connected.class);
                            startActivity(intent);
                            Toast.makeText(getApplicationContext(), R.string.title_connected_to, Toast.LENGTH_SHORT).show();
                            Log.v("Log", "Connected");
                            break;
                        case BTHandler.STATE_NONE:
                            Toast.makeText(getApplicationContext(), R.string.title_not_connected, Toast.LENGTH_SHORT).show();
                            break;
                    }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btHandler = new BTHandler(MainActivity.this, mHandler);
        b1 = (Button) findViewById(R.id.connect);
        b1.setOnClickListener(this);
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        //init();

        if (mAdapter == null) {
            Toast.makeText(getApplicationContext(), R.string.device_not_supported, Toast.LENGTH_LONG).show();
            finish();
        } else {
            if (!mAdapter.isEnabled()) {
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(intent, 1);
            }
        }
        //BTHandler btHandler = new BTHandler(MainActivity.this, mHandler);
        //btHandler.connect("");
    }

    public void onClick(View v) {
        int id = v.getId();
        //String voltage = ("ATRV");

        switch (id) {
            case R.id.connect:
                onConnect(); //Operation
                Log.v("Log", "Pressed onClick");
                break;
            /*case R.id.getValue:
                btHandler.write(voltage);
                Log.v("Log", "getValue" + voltage);
                break;*/
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), R.string.enable_bluetooth, Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void onConnect() {
        ArrayList deviceStrs = new ArrayList();
        final ArrayList<String> devices = new ArrayList();

        BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
        Set pairedDevices = mAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (Object device : pairedDevices) {
                BluetoothDevice bdevice = (BluetoothDevice) device;
                deviceStrs.add(bdevice.getName() + "\n" + bdevice.getAddress());
                devices.add(bdevice.getAddress());
            }
        }

        // show list
        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.select_dialog_singlechoice,
                deviceStrs.toArray(new String[deviceStrs.size()]));

        alertDialog.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                int position = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                String deviceAddress = devices.get(position);

                btHandler.connect(deviceAddress);
                //btHandler.write();

            }
        });
        alertDialog.setTitle("Paired devices");
        alertDialog.show();
    }
public class BTHandler {

    public static final int STATE_NONE = 0;       // we're doing nothing
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
    public static final int STATE_CONNECTED = 3;  // now connected to a remote device

    final ArrayList<String> devices = new ArrayList();
    private final Handler mHandler;
    private BluetoothAdapter mAdapter;
    private BluetoothDevice device;
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    private BluetoothSocket socket;
    private String status;
    private int mState;
    private boolean connectionStatus = false;

    public BTHandler(Context context, Handler handler) { // Konstruktor
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        mHandler = handler;
    }

    public void write(String s) {
        mConnectedThread.sendRawCommand(s);
        Log.v("write", "write");
    }

    /*
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) {
        }
    }
    */
    public void connect(String deviceAddress) {
        mConnectThread = new ConnectThread(deviceAddress);
        mConnectThread.start();
    }

    private void guiHandler(int what, int arg1, String obj) {
        Message msg = mHandler.obtainMessage();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.sendToTarget();
    }

    private class ConnectThread extends Thread {
        BluetoothSocket tmp = null;
        private BluetoothSocket mmSocket;

        public ConnectThread(String deviceAddress) {
            mAdapter = BluetoothAdapter.getDefaultAdapter();
            device = mAdapter.getRemoteDevice(deviceAddress);

            BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
            BluetoothDevice device = mAdapter.getRemoteDevice(deviceAddress);
            UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
            try {
                tmp = device.createRfcommSocketToServiceRecord(uuid);
                //socket.connect();
                //Log.v("connect", "connect");
            } catch (IOException e) {
                //e.printStackTrace();
                //Log.v("exception", "e");
            }
            mmSocket = tmp;
        }

        public void run() {
            // Cancel discovery because it will slow down the connection
            mAdapter.cancelDiscovery();
            byte[] buffer = new byte[1024]; // buffer store for the stream
            int bytes;

            try {
                // Connect the device through the socket. This will block
                // until it succeeds or throws an exception
                mmSocket.connect();
                Log.v("connect", "connect");
            } catch (IOException connectException) {
                // Unable to connect; close the socket and get out
                try {
                    mmSocket.close();
                    Log.v("close", "close");
                } catch (IOException closeException) {
                }
                guiHandler(Constants.TOAST, Constants.SHORT, "Connection Failed");
                return;
            }
            guiHandler(Constants.CONNECTION_STATUS, Constants.STATE_CONNECTED, "");
            mConnectedThread = new ConnectedThread(mmSocket);
            mConnectedThread.start();
        }
    }

    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        private ObdMultiCommand multiCommand;

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

            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;

            try {
                //RPMCommand engineRpmCommand = new RPMCommand();
                //SpeedCommand speedCommand = new SpeedCommand();
                ModuleVoltageCommand voltageCommand = new ModuleVoltageCommand();

                while (!Thread.currentThread().isInterrupted()) {
                    //engineRpmCommand.run(mmInStream, mmOutStream); //(socket.getInputStream(), socket.getOutputStream());
                    //speedCommand.run(mmInStream, mmOutStream); //(socket.getInputStream(), socket.getOutputStream());
                    voltageCommand.run(socket.getInputStream(), socket.getOutputStream());
                    // TODO handle commands result
                    //Log.d("Log", "RPM: " + engineRpmCommand.getFormattedResult());
                    //Log.d("Log", "Speed: " + speedCommand.getFormattedResult());
                    Log.v("Log", "Voltage: " + voltageCommand.getFormattedResult());
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

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

            OBDcmds();
            // Keep listening to the InputStream until an exception occurs
            while (connectionStatus) {
                sendMultiCommand();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        // CALL this to MainActivity
        public void sendRawCommand(String command) {
            try {
                new OdbRawCommand(command);

            } catch (Exception e) {
                Log.v("sendRawCommand", "e");
            }
        }

        private void OBDcmds() { // execute commands

            try {
                new EchoOffCommand().run(socket.getInputStream(), socket.getOutputStream());
                new LineFeedOffCommand().run(socket.getInputStream(), socket.getOutputStream());
                new TimeoutCommand(100).run(socket.getInputStream(), socket.getOutputStream());
                new SelectProtocolCommand(ObdProtocols.AUTO).run(socket.getInputStream(), socket.getOutputStream()); //ISO_15765_4_CAN

            } catch (Exception e) {
                Log.v("OBDcmds", "e");
                // handle errors
            }
        }
        /*
        // Call this from the main activity to send data to the remote device
        public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) {
            }
        }
        */

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

        public void sendMultiCommand() {
            try {
                // RUN some code here
            } catch (Exception e) {
            }
        }
    }
}

错误原因如下:

BTHandler btHandler;
你正在这样做:

btHandler.write(voltage);
但是对象是空引用的

您需要在
oncreate
中初始化BTHandler…
或者更好:

使用服务以便可以将所有活动绑定到该服务

附言:
请注意,MainActivity的BTHandler与SPA类中声明的BTHandler不同。。。因此,尽管btHandler是在MainActivity中构造和工作的,但并不意味着它将在其他活动/类中工作

您得到了什么错误?发布日志!。。。我认为错误是因为你正在更改活动,而BT连接正在丢失…发布日志(完全忘记了它)。是的,我也这么认为,但我也认为我需要在活动中启动我的bluetoothhandler“这是我在主活动中启动我的bluetoothhandler的地方”是的,但是
SPA
有不同的变量,你必须初始化它们again@cricket-007是的,我想。但是我该怎么做呢?我已经更新了帖子,展示了
write
方法。奇怪的是,当我有
新的OdbRawCommand(命令)时,它是空的(顺便说一句,我正在使用obdiiapi)。也许你能告诉我怎么做?你能告诉我怎么在onCreate中初始化BTHandler吗?