简体   繁体   English

使蓝牙通过Activites保持连接

[英]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. 我正在研究需要蓝牙作为Android设备和微控制器芯片之间通信方式的项目。

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. 我不确定,什么变量或应如何将所需的变量分配到SharedPreferences中,以使我在使用应用程序时始终保持连接状态。 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. 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. 服务始终保持活动状态,而不管程序始终在运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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