簡體   English   中英

使藍牙通過Activites保持連接

[英]Making the Bluetooth stay connected through Activites

我正在研究需要藍牙作為Android設備和微控制器芯片之間通信方式的項目。

我已經成功完成了可以與設備配對並建立連接並將數據發送到芯片的部分,並且工作正常。

我的程序的流程是: 起始頁>輸入文本/字符串>連接到設備>發送數據

這里的主要問題是,如果要輸入文本/字符串>連接到設備,但是在連接之后,我決定要在上一頁中進行更改。 因此,我單擊返回,藍牙連接已停止。 它不會保持連接狀態。

因此,我的主要思想是提出“藍牙連接頁面”,使我可以先連接到設備,然后再輸入文本/字符串。 這樣,如果我決定進行其他活動或選項卡,則只需在選項卡上滑動並輸入所需內容,每個選項卡中都會有一個“發送”按鈕,使我可以直接發送數據而無需再次連接。 我目前對此感到困惑。

藍牙活動:

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();
    }



}

我不確定,什么變量或應如何將所需的變量分配到SharedPreferences中,以使我在使用應用程序時始終保持連接狀態。 簡而言之,當我連接一次后,一直保持連接狀態。 我希望有人可以幫助我。

提前致謝。

SDK中有一個藍牙示例。 如果您遵循它,您將看到他們在服務中執行藍牙操作,並且活動連接到該服務。 服務始終保持活動狀態,而不管程序始終在運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM