简体   繁体   中英

Making the Bluetooth stay connected through Activites

I'm working on my project which needs Bluetooth as a form of communication between an Android Device and a Microcontroller chip.

I have successfully done the part where I can pair up with a device and get connected and send the data off to the chip and it is working fine.

The flow of my Program is: Start Page>Input Text/String>Connect to a Device>Send Data .

The main problem here is, if I were to Input Text/String>Connect to a Device, but after connecting, I decide that I want to change something in the previous page. So I click back and the Bluetooth connection is stopped. It doesn't stay connected.

So my main idea was to bring forward the Bluetooth Connection Page, allowing me to connect to a Device first then go on to inputting my text/string. So that way, if I decide to make another activity or a tab, I can just swipe through the tabs and input whatever I want and there will be a Send button in each tab, allowing me to send Data straight without reconnecting again. I'm currently stuck on this.

Bluetooth Activity:

public class bluetoothtest extends Activity {
    /** Called when the activity is first created. */

    SharedPreferences sPrefs;

    //Variables
    final byte ANIMATION_MODE=1;
    final byte PICTURE_MODE=2;
    final byte TEXT_MODE=3;
    int a,b,c,d;

    int count = 0, click = 0;

    //TextView
    TextView btStatus;

    //ListView
    ListView listViewPaired;
    ListView deviceList;
    ListView chatList;

    //EditText
    EditText contentRow1, contentRow2, contentRow3, contentRow4;

    //Buttons
    Button buttonSearch, buttonConnect;
    ToggleButton bluetoothStatus;

    //Bluetooth Related
    BluetoothSocket socket;
    BluetoothDevice bdDevice;
    BluetoothClass bdClass;
    deviceListAdapter mAdapter;
    ChatListAdapter chAdapter;
    Context mContext;
    private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    private readThread readThread = null;
    private String BlueToothAddress;


    //Array List/Adapter
    ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
    ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
    ArrayList<String> arrayListpaired;
    ArrayAdapter<String> adapter;
    private ArrayList<deviceListItem> list;
    private ArrayList<SiriListItem> delist;

   //Misc
    static HandleSeacrh handleSeacrh;
    private ButtonClicked clicked;



    @Override 
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //TextView
        btStatus = (TextView) findViewById(R.id.btStatus);

        //ListView
        deviceList = (ListView) findViewById(R.id.deviceList);
        chatList = (ListView) findViewById(R.id.chatList);

        //EditText
        contentRow1 = (EditText) findViewById(R.id.contentRow1);
        contentRow2 = (EditText) findViewById(R.id.contentRow2);
        contentRow3 = (EditText) findViewById(R.id.contentRow3);
        contentRow4 = (EditText) findViewById(R.id.contentRow4);

        //Buttons
        buttonSearch = (Button) findViewById(R.id.buttonSearch);
        buttonConnect = (Button) findViewById(R.id.connectBtn);
        bluetoothStatus = (ToggleButton) findViewById(R.id.btStatusBtn);

        //Array List/Adapter
        list = new ArrayList<deviceListAdapter.deviceListItem>();
        delist = new ArrayList<ChatListAdapter.SiriListItem>();
        chAdapter = new ChatListAdapter(this, delist);
        mAdapter = new deviceListAdapter(this, list);
        deviceList.setAdapter(chAdapter);
        chatList.setAdapter(mAdapter);

        //Misc
        clicked = new ButtonClicked();
        handleSeacrh = new HandleSeacrh();
        deviceList.setOnItemClickListener(mDeviceClickListener);

        bluetoothStatus.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                bluetoothOnOff();

            }
        });

        //Button Connect OnClickListener
        buttonConnect.setOnClickListener(new View.OnClickListener() {

            @SuppressLint("NewApi")
            @Override
            public void onClick(View arg0) {
                if (count == 0) {
                    Toast.makeText(bluetoothtest.this,
                            "Please connect to a device first.",
                            Toast.LENGTH_LONG).show();
                } 
                // Need API=14
                else if (!socket.isConnected()) {
                        Toast.makeText(bluetoothtest.this,
                                "Connecting! Please wait.",
                                Toast.LENGTH_LONG).show();
                    }
                else {
                    try {
                        sendMessageHandle(contentRow1.getText().toString(), contentRow2.getText().toString(), contentRow3.getText().toString(), contentRow4.getText().toString());
                        //sendMessageHandle(contentRow2.getText().toString());

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }
        });

        sPrefs = getSharedPreferences("storeData", MODE_PRIVATE);
        if(((byte) sPrefs.getInt("Mode", 1) == TEXT_MODE)){

            contentRow1.setText(sPrefs.getString("firstRow", " "));
            contentRow2.setText(sPrefs.getString("secondRow", " "));
            contentRow3.setText(sPrefs.getString("thirdRow", " "));
            contentRow4.setText(sPrefs.getString("fourthRow", " "));
        }

        IntentFilter discoveryFilter = new IntentFilter(
                BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(myReceiver, discoveryFilter);

        IntentFilter foundFilter = new IntentFilter(
                BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(myReceiver, foundFilter);

        IntentFilter btState = new IntentFilter(
                BluetoothAdapter.ACTION_STATE_CHANGED);
        this.registerReceiver(myReceiver, btState);
    }
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        buttonSearch.setOnClickListener(clicked);
        if(bluetoothAdapter.isEnabled())
        {
            bluetoothStatus.setChecked(true);
            //bluetoothStatus.setBackgroundColor(Color.GREEN);
            btStatus.setText("Bluetooth Status: Enabled");
            btStatus.setBackgroundColor(Color.GREEN);
        }else if(!bluetoothAdapter.isEnabled())
        {
            bluetoothStatus.setChecked(false);
            //bluetoothStatus.setBackgroundColor(Color.RED);
            btStatus.setText("Bluetooth Status: Disabled");
            btStatus.setBackgroundColor(Color.RED);
        }

    }



    class ButtonClicked implements OnClickListener
    {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
            case R.id.buttonSearch:
                //arrayListBluetoothDevices.clear();
                startSearching();
                break;
            default:
                break;
            }
        }
    }
    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Message msg = Message.obtain();
            String action = intent.getAction();

//            if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
//              bluetoothOnOff();
//            }
            if(BluetoothDevice.ACTION_FOUND.equals(action)){
                Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT).show();

                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                if (device.getBondState() != BluetoothDevice.BOND_BONDED) 
                { delist.add(new SiriListItem(device.getName() + "\n" + device.getAddress(), action, action, action, false));
                    mAdapter.notifyDataSetChanged();
                    deviceList.setSelection(delist.size() - 1);
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                if (deviceList.getCount() == 0) {
                    delist.add(new SiriListItem( "Did not find any bluetooth device", action, action, action, false));
                    mAdapter.notifyDataSetChanged();
                    deviceList.setSelection(list.size() - 1);
                }
                buttonSearch.setText("Search again");
                }
            }           
        };


    private void bluetoothOnOff(){

        if(!bluetoothAdapter.isEnabled())
        {
            bluetoothAdapter.enable();
            String text = "Bluetooth Status: Enabled";
            bluetoothStatus.setChecked(false);
            //bluetoothStatus.setBackgroundColor(Color.GREEN);
            btStatus.setText(text);
            btStatus.setBackgroundColor(Color.GREEN);
        }else if(bluetoothAdapter.isEnabled()){
            String text = "Bluetooth Status: Disabled";
            bluetoothAdapter.disable();
            bluetoothStatus.setChecked(true);
            //bluetoothStatus.setBackgroundColor(Color.RED);
            btStatus.setText(text);
            btStatus.setBackgroundColor(Color.RED);
        }

    }


    class HandleSeacrh extends Handler
    {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 111:

                break;

            default:
                break;
            }
        }
    }

    //SharedPreferences sp;

private void sendMessageHandle(String msg, String msg2, String msg3, String msg4) throws InterruptedException {

        final byte ANIMATION_MODE=1;
        final byte PICTURE_MODE=2;
        final byte TEXT_MODE=3;
        final int k = 5;

        int temp,row;

        sPrefs = getSharedPreferences("storeData",MODE_PRIVATE);

        byte mode = (byte) sPrefs.getInt("Mode",1);
        byte [] pictureData = new byte [129];

        if (socket == null) {
            Toast.makeText(mContext, "No connection", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        try {
            OutputStream outputStream = socket.getOutputStream();
            if(mode==TEXT_MODE){
                //TextMode Signal
                outputStream.write(4);
                Thread.sleep(500);

                //Row 1 Message / Scroll
                outputStream.write(0);
                if(sPrefs.getBoolean("scrollRow1", false))
                        {}else 
                        {outputStream.write(6);}
                msg.getBytes();
                if(msg.getBytes().length > 0)
                {a = 1;
                outputStream.write(msg.getBytes());
                outputStream.write(32);}


                //Row 2 Message / Scroll
                outputStream.write(1);
                if(sPrefs.getBoolean("scrollRow2", false))
                {}else
                {outputStream.write(6);}
                msg2.getBytes();
                if(msg2.getBytes().length > 0)
                {b = 1;
                outputStream.write(msg2.getBytes());
                outputStream.write(32);}


                //Row 3 Message / Scroll
                outputStream.write(2);
                if(sPrefs.getBoolean("scrollRow3", false))
                {}else
                {outputStream.write(6);}
                msg3.getBytes();
                if(msg3.getBytes().length > 0)
                {c = 1;
                outputStream.write(msg3.getBytes());
                outputStream.write(32);}


                //Row 4 Message / Scroll
                outputStream.write(3);
                if(sPrefs.getBoolean("scrollRow4", false))
                {}else
                {outputStream.write(6);}
                msg4.getBytes();
                if(msg4.getBytes().length > 0)
                {d = 1;
                outputStream.write(msg4.getBytes());
                outputStream.write(32);}

                //End of Signal Transmission
                outputStream.write(k);
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(a == 1)
            {   a = 0;
            list.add(new deviceListItem(msg, false));
            }
        if(b == 1)
            {   b = 0;
            list.add(new deviceListItem(msg2, false));
            }
        if(c == 1)
            {   c = 0;
        list.add(new deviceListItem(msg3, false));
            }
        if(d == 1)
            {   d = 0;
        list.add(new deviceListItem(msg4, false));
            }

        mAdapter.notifyDataSetChanged();
        chatList.setSelection(list.size() - 1);
    }

public void cancle() {
    try {
        socket.close();
    } catch (IOException e) {
    }
}

    private class clientThread extends Thread {
        public void run() {

            try {
                //
                bdDevice = bluetoothAdapter.getRemoteDevice(BlueToothAddress);
                socket = bdDevice.createRfcommSocketToServiceRecord(UUID
                        .fromString("00001101-0000-1000-8000-00805F9B34FB"));
                Message msg2 = new Message();
                msg2.obj = "Please wait, connecting to server: "
                        + BlueToothAddress;
                msg2.what = 0;
                LinkDetectedHandler.sendMessage(msg2);
                socket.connect();
                Log.i("tag", "This is the pairing section");

                Message msg = new Message();
                msg.obj = "Device connected. Sending message is allowed.";
                msg.what = 0;
                LinkDetectedHandler.sendMessage(msg);

                readThread = new readThread();
                readThread.start();
                click++;

            } catch (IOException e) {
                Message msg = new Message();
                msg.obj = "Error! Can't connect to device. Please try again.";
                msg.what = 0;
                LinkDetectedHandler.sendMessage(msg);
                click--;

            }
        }
    };

    private Handler LinkDetectedHandler = new Handler() {
        public void handleMessage(Message msg) {
            Toast.makeText(getApplicationContext(), (String) msg.obj,
                    Toast.LENGTH_SHORT).show();
            if (msg.what == 1) {
                list.add(new deviceListItem((String) msg.obj,true));
            } else {
                list.add(new deviceListItem((String) msg.obj, false));
            }
            mAdapter.notifyDataSetChanged();
            chatList.setSelection(list.size() - 4);
        }

    };


    private class readThread extends Thread {
        public void run() {

            byte[] buffer = new byte[1024];
            int bytes;
            InputStream mmInStream = null;
            String tmp = null;
            try {
                mmInStream = socket.getInputStream();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            while (true) {
                try {
                    // read the data from the inputStream 
                    if ((bytes = mmInStream.read(buffer)) > 0) 
                    {
                        for (int i = 0; i < bytes; i++) {
                            tmp = "" + buffer[i];
                            String st = new String(tmp);
                            tmp = null;
                            Message msg = new Message();
                            msg.obj = st;
                            msg.what = 1;
                        }
                    }
                } catch (IOException e) {
                    try {
                        mmInStream.close();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    break;
                }
            }
        }
    }

    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // Cancel discovery because it's costly and we're about to connect

                        bluetoothAdapter.cancelDiscovery();
                        System.out.println("Bluetooth Adapter2 = "+bluetoothAdapter.cancelDiscovery());
                        SiriListItem item = delist.get(arg2);
                        mAdapter.notifyDataSetChanged();
                        // When device being clicked
                        count++;
                        click = 1;
                        // Get the device MAC address, which is the last 17 chars in the
                        // View
                        String info = item.message;
                        String address = info.substring(info.length() - 17);
                        BlueToothAddress = address;
                        if (click == 1) {
                            clientThread ct = new clientThread();
                            ct.start();

        }
};
};


    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        unregisterReceiver(myReceiver);
        super.onDestroy();
    }



}

I'm not sure, what variable or how should I assign the variables needed into SharedPreferences to allow me to stay connected all the time when I'm on the application. In short, staying connected all the time, when I've connected once. I hope someone can help me out on this.

Thanks in advance.

There is a Bluetooth sample in the SDK. If you follow it you will see they are performing Bluetooth operations in a service and the activities connect to that service. A service stays active regardless of activities all the time your program is running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM