保留蓝牙连接,直到应用程序关闭

时间:2017-08-03 10:42:36

标签: android service bluetooth android-bluetooth

我制作了一个连接蓝牙的应用程序,并在活动中发送和接收数据。现在我在应用程序中有更新,并且必须创建另一个连接到相同蓝牙设备并传输数据的活动。所以我打算在我的第二个活动中连接到蓝牙设备,这个活动有一些按钮需要另外一个活动。我需要在使用按钮从第二个活动调用的活动中保留我在第二个活动中所做的蓝牙连接,直到用户按下第二个活动的退回按钮(退出第二个活动)。请解释我应该如何更改代码以实现此目的。这是我当前的代码,用于单活动蓝牙连接。

public class ViewBoardStatus extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_board_status);

        mOutStringBuffer = new StringBuffer("");

        IntentFilter filter = new IntentFilter();

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

        List<String> paireddevicesarray = new ArrayList<>();

        int iNoOfPariedDev = pairedDevices.size();
        int iDeviceCntr = 0;
        DevAddressString = new String[iNoOfPariedDev][2];

        for (BluetoothDevice device : pairedDevices)
        {

            DevAddressString[iDeviceCntr][0] = device.getAddress();
            DevAddressString[iDeviceCntr][1] = device.getName();
            iDeviceCntr++;
            if (iDeviceCntr > iNoOfPariedDev)
                break;
        }

        ArrayList<String> aList = new ArrayList<String>();

        aList.add("Select Device");
        for (int i = 0; i < iDeviceCntr; i++)
        {
            aList.add(DevAddressString[i][1]);

        }

        final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, aList);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp_paireddevices.setAdapter(dataAdapter);

        sp_paireddevices.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {

            public void onItemSelected(AdapterView<?> parentView,
                                       View selectedItemView, int position, long id) {
                // Object item = parentView.getItemAtPosition(position);

                Log.e(TAG, "Executing On ITEM SELECTED");

                int iLoc = sp_paireddevices.getSelectedItemPosition();

                if (iLoc != 0)
                {
                    Toast.makeText(getApplicationContext(), " Connecting to hardware please wait..", Toast.LENGTH_SHORT).show();
                    iBTDevSelcted = 1;
                    Log.e(TAG, "Toast message of Connecting");
                    address = DevAddressString[iLoc - 1][0];
                    Log.e(TAG, "Calling OnResume Function");
                    onResume();

                }
                else
                {
                    Toast.makeText(getApplicationContext(), " Please select Bluetooth Device", Toast.LENGTH_SHORT).show();
                }

            }

            public void onNothingSelected(AdapterView<?> arg0) {// do nothing
            }

        });

        lvParaHeader.setOnTouchListener(new View.OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                if(touchSource == null)
                    touchSource = v;

                if(v == touchSource)
                {
                    lvParaValue.dispatchTouchEvent(event);
                    if(event.getAction() == MotionEvent.ACTION_UP)
                    {
                        clickSource = v;
                        touchSource = null;
                    }
                }

                return false;
            }
        });

        lvParaValue.setOnTouchListener(new View.OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                if(touchSource == null)
                    touchSource = v;

                if(v == touchSource)
                {
                    lvParaHeader.dispatchTouchEvent(event);
                    if(event.getAction() == MotionEvent.ACTION_UP)
                    {
                        clickSource = v;
                        touchSource = null;
                    }
                }

                return false;
            }
        });

        lvParaHeader.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(parent == clickSource) {
                    // Do something with the ListView was clicked
                }
            }
        });

        lvParaValue.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(parent == clickSource) {
                    // Do something with the ListView was clicked
                }
            }
        });


        lvParaHeader.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if(view == clickSource)
                    lvParaValue.setSelectionFromTop(firstVisibleItem, view.getChildAt(0).getTop() + offset);
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {}
        });

        lvParaValue.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if(view == clickSource)
                    lvParaHeader.setSelectionFromTop(firstVisibleItem, view.getChildAt(0).getTop() + offset);
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {}
        });


        sp_datatype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
            {
                Log.e(l,"Starting ON Item Selected");


                if (sp_paireddevices.getSelectedItemPosition()>0)
                {

                    if (sp_datatype.getSelectedItemPosition() == 1) {

                        sGetRequest = sGetElectricalPara;
                        sendMessage(sGetRequest);

                    }

                    if (sp_datatype.getSelectedItemPosition() == 2) {
                        sGetRequest = sGetGprsPara;
                        sendMessage(sGetRequest);

                    }

                    if (sp_datatype.getSelectedItemPosition() == 3) {
                        sGetRequest = sGetSystemPara;
                        sendMessage(sGetRequest);

                    }

                    if (sp_datatype.getSelectedItemPosition() == 4) {
                        sGetRequest = sGetRS485Para;
                        sendMessage(sGetRequest);
                    }
                }
                else
                    Toast.makeText(getApplicationContext(), " Connect to a Device and Refresh ", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent)
            {

            }
        });

        bt_Refresh.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Log.e(l,"Refresh Button OnClick");

                if (sp_paireddevices.getSelectedItemPosition()>0)
                {

                    if (sp_datatype.getSelectedItemPosition() == 0) {
                        Toast.makeText(getApplicationContext(), " Select a Parameter to Refresh ", Toast.LENGTH_SHORT).show();
                    }


                    if (sp_datatype.getSelectedItemPosition() == 1) {
                        sGetRequest = sGetElectricalPara;
                        sendMessage(sGetRequest);
                        Log.e(l, "Send Message Called");

                    }

                    if (sp_datatype.getSelectedItemPosition() == 2) {
                        sGetRequest = sGetGprsPara;
                        sendMessage(sGetRequest);
                    }

                    if (sp_datatype.getSelectedItemPosition() == 3) {
                        sGetRequest = sGetSystemPara;
                        sendMessage(sGetRequest);
                    }

                    if (sp_datatype.getSelectedItemPosition() == 4) {
                        sGetRequest = sGetRS485Para;
                        sendMessage(sGetRequest);
                    }
                    Log.e(l, "Send Message Called");
                }
                else
                    Toast.makeText(getApplicationContext(), " Connect to a Device and Refresh ", Toast.LENGTH_SHORT).show();
            }
        });


        h = new Handler()
        {

            public void handleMessage(android.os.Message msg)
            {
                Log.e(l, "Starting Handler");

                int strlen;

                switch (msg.what)
                {
                    case RECIEVE_MESSAGE:                                                   
                        Log.d(l, "data received = " );
                        byte[] readBuf = (byte[]) msg.obj;
                        String strIncom = new String(readBuf, 0, msg.arg1);                
                        String strMsg = new String();
                        sb.append(strIncom);                                                
                        int endOfLineIndex = sb.indexOf("#");                               


                        if (endOfLineIndex > 0)
                        {                                            // if end-of-line,
                            sJsonData = sb.substring(1, endOfLineIndex); // extract string

                            sb.delete(0, sb.length());
                            // and clear

                            try
                            {
                                Log.e(l, "Starting Try of Handler");

                                    Log.e(l, "Data Received: "+sJsonData);
                                    strlen = sJsonData.length();
                                    Log.e(l, "String Length Obtained");
                                    JSONObject mainobject = new JSONObject(sJsonData);
                                    Log.e(l, "main object created");
                                    sDataType = mainobject.getString("DATA_TYPE");
                                    Log.e(l, "Data Type Obtained");
                                    //tv_jsonlength.setText(String.valueOf(strlen));
                                    //tv_JsonPara.setText(TempHeader);

                                    iSelectedParaPostion=sp_datatype.getSelectedItemPosition();

                                    if(sDataType.trim().equalsIgnoreCase("PARA"))
                                    {
                                        if(iSelectedParaPostion==1)
                                        {
                                            sCurrentJsonData = sJsonData;
                                            Log.e(l, "sCurrentJsonData set to sJsonData");
                                            //tv_jsonstring.setText(sCurrentJsonData);
                                            jsonparseelectricalpara();
                                        }
                                    }

                                    if(sDataType.trim().equalsIgnoreCase("GPRS"))
                                    {
                                        if(iSelectedParaPostion==2)
                                        {
                                            sCurrentJsonData = sJsonData;
                                            Log.e(l, "sCurrentJsonData set to sJsonData");
                                            //tv_jsonstring.setText(sCurrentJsonData);
                                            jsonparsegprsdata();
                                        }
                                    }

                                    if(sDataType.trim().equalsIgnoreCase("SYSTEM"))
                                    {
                                        if(iSelectedParaPostion==3)
                                        {
                                            sCurrentJsonData = sJsonData;
                                            Log.e(l, "sCurrentJsonData set to sJsonData");
                                            //
                                            // tv_jsonstring.setText(sCurrentJsonData);
                                            jsonparseSystem();
                                        }
                                    }

                            }
                            catch (Exception e)
                            {
                                Log.e(l, "CATCH OF HANDLER");
                            }

                        }
                        break;
                }

            }
        };

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
        checkBTState();

    }//oncreate

    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(mBluetoothAdapter==null) {
            //        Log.d(TAG, "error, bluetooth not supported");
        } else {
            if (mBluetoothAdapter.isEnabled()) {
                //           Log.d(TAG, "...Bluetooth ON...");
            } else {
                //Prompt user to turn on Bluetooth
                tvconnectionstatus.setText("");
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);
            }
        }
    }


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

    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
    {
        if (Build.VERSION.SDK_INT >= 10)
        {

            try
            {
                final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[]{UUID.class});
                Log.e(TAG, "Bluetooth Socket Creation TRY EXECUTED");
                return (BluetoothSocket) m.invoke(device, MY_UUID);
            }

            catch (Exception e2)
            {
                errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
                Log.e(TAG, "Bluetooth Socket Creation CATCH EXECUTED");
            }
        }
        Log.e(TAG, "Exiting Socket Creation Method");
        return device.createRfcommSocketToServiceRecord(MY_UUID);
    }

    public void onResume()
    {
        super.onResume();

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);


        Log.e(TAG, "Starting OnResume Method");
        if (iBTDevSelcted == 0) {
            Toast.makeText(getApplicationContext(), " Please select Bluetooth Device", Toast.LENGTH_SHORT).show();
            return;
        }


        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        Log.e(TAG, "Obtaining REMOTE DEVICE address");


        try {
            btSocket = createBluetoothSocket(device);
            Log.e(TAG, "BT SOCKET Created");
        } catch (IOException e) {
            errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
        }

        mBluetoothAdapter.cancelDiscovery();
        Log.e(TAG, "BT Discovery CANCELLED");

        try
        {

            Log.e(TAG, "TRY STATEMENT OF BT CONNECTION CREATION");
            btSocket.connect();
            String connectedto = "Connected to: " + sp_paireddevices.getSelectedItem().toString();
            tvconnectionstatus.setText(connectedto);

        }
        catch (IOException e)
        {

            Log.e(TAG, "CATCH STATEMENT OF BLUETOOTH CONNECTION CREATION");
            try {

                btSocket.close();
                Log.e(TAG, "Bluetooth Socket Closed");
                tvconnectionstatus.setText("");
            } catch (IOException e2) {
                errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
                Log.e(TAG, "Unable to Close bluetooth connection");
            }
        }

        // Create a data stream so we can talk to server.
        //    Log.d(TAG, "...Create Socket...");

        mConnectedThread = new ConnectedThread(btSocket);
        Log.e(TAG, "Connection Thread Created");
        mConnectedThread.start();
        Log.e(TAG, "Connection Thread Started");
    }

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

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

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

    private class ConnectedThread extends Thread
    {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

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

            // Get the input and output streams, using temp objects because
            // member streams are final
            try
            {
                Log.e(TAG, "Trying to get Temp Input/Output Stream");
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
                Log.e(TAG, "Input/Output Stream Obtained");
            }
            catch (IOException e)
            {
                Log.e(TAG, "I/O Stream CATCH STATEMENT");
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;

        }

        public void run()
        {
            Log.e(TAG, "Starting RUN Method");
            byte[] buffer = new byte[1024];  // buffer store for the stream
            int bytes; // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs
            while (true)
            {
                try {


                    Log.e(TAG, "TRY of RUN Method Started");
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"

                    h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler

                    Log.e(l,"Run Executed");
                    Log.e(TAG, "TRY of RUN Method Completed");
                } catch (IOException e)
                {
                    Log.e(TAG, "CATCH of RUN Method");
                    break;
                }
            }


        }

        public void write(String s) throws IOException
        {
            mmOutStream.write(s.getBytes());
            tvconnectionstatus.setText(s);
            sGetRequest=sReset;

        }

    }//connectthread

    private void sendMessage(String message)
    {
        ConnectedThread ct;
        Log.e(l,"Connected Thread Object Created");

        ct = mConnectedThread;

        try {
            ct.write(message);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}//class

0 个答案:

没有答案