我正在建立一个蓝牙应用程序,用于通信另一个蓝牙设备。我能够扫描并获得可用设备的列表

时间:2015-09-24 06:43:33

标签: android bluetooth

package com.ubitech.tokencallingsystem;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class BluetoothActivity extends Activity{
    private final static UUID uuid = UUID.fromString("38bf8160-61ce-11e5-a837-0800200c9a66");
    private BluetoothAdapter bluetoothAdapter;
    private ToggleButton toggleBtn;
    private Button scanBtn;
    private ListView listView;
    @SuppressWarnings("rawtypes")
    private ArrayAdapter adapter;
    private static final int ENABLE_BT_REQUEST_CODE = 1;

    @SuppressWarnings("rawtypes")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bluetooth_activity);
        toggleBtn = (ToggleButton) findViewById(R.id.toggleButton);
        scanBtn = (Button) findViewById(R.id.scan);
        listView = (ListView) findViewById(R.id.listView);
        adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1);
        listView.setAdapter(adapter);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String  itemValue = (String) listView.getItemAtPosition(position);
                String MAC = itemValue.substring(itemValue.length() - 17);
                Toast.makeText(getApplicationContext(), itemValue+"="+MAC, Toast.LENGTH_SHORT).show();
                BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(MAC);
                // Initiate a connection request in a separate thread
                ConnectingThread t = new ConnectingThread(bluetoothDevice);
                t.start();
                AcceptThread th = new AcceptThread();
                th.start();
                System.out.println("In itemonclick listner");
            }
        });
    }

    public void onToggleClicked(View view){
        //adapter.clear();
        if (bluetoothAdapter == null) {
            Toast.makeText(getApplicationContext(), "Oops! Bluetooth not supported.", Toast.LENGTH_SHORT).show();
        } else {
            if(toggleBtn.isChecked()){
                scanDevices(view);
            } else{
                Toast.makeText(getApplicationContext(), "Turning off bluetooth..", Toast.LENGTH_SHORT).show();
                adapter.clear();
                bluetoothAdapter.disable();
            }
        }
    }
    public void scanDevices(View view){
        adapter.clear();
        if(!bluetoothAdapter.isEnabled()){
            Toast.makeText(getApplicationContext(), "Turning on bluetooth..", Toast.LENGTH_SHORT).show();
            Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetoothIntent, ENABLE_BT_REQUEST_CODE); 
            discoverDevices();
         }else{
             /* Toast.makeText(getApplicationContext(), "Bluetooth has already been enabled." +
                      "\n" + "Scanning for available nearby bluetooth devices..",
              Toast.LENGTH_SHORT).show();*/
              discoverDevices();
         }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ENABLE_BT_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
               // Toast.makeText(getApplicationContext(), "Bluetooth is now enabled.", Toast.LENGTH_SHORT).show();
                discoverDevices();

            } else {
               // Toast.makeText(getApplicationContext(), "Bluetooth is not enabled.",Toast.LENGTH_SHORT).show();
                toggleBtn.setChecked(false);
            }
        }
    }

    protected void discoverDevices(){       
        if (bluetoothAdapter.startDiscovery()) {
            Toast.makeText(getApplicationContext(), "Scanning for available nearby bluetooth devices..", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "Scanning failed to start.", Toast.LENGTH_SHORT).show();
        }
    }

    private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // Whenever a remote Bluetooth device is found
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // Add the name and address to an array adapter to show in a ListView
                adapter.add(bluetoothDevice.getName() + "\n"
                        + bluetoothDevice.getAddress());
            }
            if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                final int state        = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
                final int prevState    = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);

                if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
                    Toast.makeText(getApplicationContext(), "Paired.", Toast.LENGTH_SHORT).show();
                } else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
                    Toast.makeText(getApplicationContext(), "UnPaired.", Toast.LENGTH_SHORT).show();
                }

           }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        // Register the BroadcastReceiver for ACTION_FOUND
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(broadcastReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        this.unregisterReceiver(broadcastReceiver);
    }

    private class ConnectingThread extends Thread {
        private final BluetoothSocket bluetoothSocket;
        private final BluetoothDevice bluetoothDevice;

        public ConnectingThread(BluetoothDevice device) {

            BluetoothSocket temp = null;
            bluetoothDevice = device;

            // Get a BluetoothSocket to connect with the given BluetoothDevice
            try {
                System.out.println("1");
                temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
                System.out.println("2");
            } catch (IOException e) {
                System.out.println("In catch exception connecting bt device");
                e.printStackTrace();
            }
            System.out.println("3");
            bluetoothSocket = temp;
        }

        public void run() {
            // Cancel discovery as it will slow down the connection
            System.out.println("4");
            bluetoothAdapter.cancelDiscovery();

            try {
                // This will block until it succeeds in connecting to the device
                // through the bluetoothSocket or throws an exception
                System.out.println("5");
                if(bluetoothSocket!=null){
                    bluetoothSocket.connect();
                }
                /*InputStream inputStream = bluetoothSocket.getInputStream();                                                       
                OutputStream outputStream = bluetoothSocket.getOutputStream();
                outputStream.write(new byte[] { (byte) 0xa0, 0, 7, 16, 0, 4, 0 });*/
                Log.e("","Connected");
            } catch (IOException connectException) {
                System.out.println("In connection exception thread");
                connectException.printStackTrace();
                try {
                    System.out.println("6");
                    bluetoothSocket.close();
                    System.out.println("7");
                } catch (IOException closeException) {
                    System.out.println("in connection close exception");
                    closeException.printStackTrace();
                }
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            finally {
                if (bluetoothSocket != null) {
                    try {
                        Log.d("TCS", ">>Client Close");
                        bluetoothSocket.close();    
                        finish();
                        return ;
                    } catch (IOException e) {
                        Log.e("EF-BTBee", "", e);
                    }
                }
            }

            // Code to manage the connection in a separate thread

              // manageBluetoothConnection(bluetoothSocket);

        }

    }

    private class AcceptThread extends Thread {
        private final BluetoothServerSocket mmServerSocket;

        public AcceptThread() {
            // Use a temporary object that is later assigned to mmServerSocket,
            // because mmServerSocket is final
            BluetoothServerSocket tmp = null;
            try {
                // MY_UUID is the app's UUID string, also used by the client code
                tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord("tcs", uuid);
            } catch (IOException e) { }
            mmServerSocket = tmp;
        }

        public void run() {
            BluetoothSocket socket = null;
            // Keep listening until exception occurs or a socket is returned
            while (true) {
                try {
                    socket = mmServerSocket.accept();
                } catch (IOException e) {
                    break;
                }
                // If a connection was accepted
                if (socket != null) {
                    // Do work to manage the connection (in a separate thread)
                    //manageConnectedSocket(socket);
                    try {
                        mmServerSocket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }

        /** Will cancel the listening socket, and cause the thread to finish */
        public void cancel() {
            try {
                mmServerSocket.close();
            } catch (IOException e) { }
        }
    }
}

这是我的活动档案。从我在哪里尝试连接另一个Android设备。但是当试图连接时没有任何反应。刚刚收到警告getBluetoothService(),没有BluetoothManagerCallback。

0 个答案:

没有答案