将蓝牙从Android连接到计算机(配对设备)

时间:2015-04-01 11:19:34

标签: java android bluetooth android-bluetooth

所以,我希望我的应用程序连接到我的电脑,然后使用android作为触摸板。我已经在网上做了很多研究,但我没有找到如何将我的手机与手机完全连接。我做了对设备功能和其他一切,我只需要连接方法,或者至少可以做到这一点。这是代码:

public class MainActivity extends Activity {
private BluetoothAdapter adapter;
private Intent turnOn;
private Set<BluetoothDevice> pairedDevices;
private ListView lv;
private Button on,off,pairedDevice,discoverable,nearDevices;
private List<BluetoothDevice> discoveredDevices = new ArrayList<BluetoothDevice>();
private  Handler mHandler;
private static final UUID MY_UUID = UUID.fromString("04c6093b-0000-1000-8000-00805f9b34fb");
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initialize();
    buttonFunc();
    find();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}



public void lista(int i){
    if(i==0) {
        final DeviceAdapter deviceAdapter = new DeviceAdapter(MainActivity.this, discoveredDevices);
        lv.setAdapter(deviceAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                pairDevice(deviceAdapter.getItem(position));
                Message.message(MainActivity.this, deviceAdapter.getItem(position).getName().toString());
            }
        });
    }
    else if(i == 1){
        List<BluetoothDevice> vecUpareni = new ArrayList<BluetoothDevice>();

        for (BluetoothDevice bt:adapter.getBondedDevices()){
            vecUpareni.add(bt);
        }
        final DeviceAdapter deviceAdapter = new DeviceAdapter(MainActivity.this,  vecUpareni);
        lv.setAdapter(deviceAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String adresa = deviceAdapter.getItem(position).getAddress();
                Method connect = getConnectMethod();
                BluetoothDevice device = deviceAdapter.getItem(position);


            }
        });
    }
}


private Method getConnectMethod () {
    try {
        return BluetoothA2dp.class.getDeclaredMethod("connect", BluetoothDevice.class);
    } catch (NoSuchMethodException ex) {
        Message.message(MainActivity.this , "Unable to connect");
        return null;
    }
}


private void pairDevice(BluetoothDevice device) {
    try {
        Log.d("pairDevice()", "Start Pairing...");
        Method m = device.getClass().getMethod("createBond", (Class[]) null);
        m.invoke(device, (Object[]) null);
        Log.d("pairDevice()", "Pairing finished.");
    } catch (Exception e) {
        Log.e("pairDevice()", e.getMessage());
    }
}

public void buttonFunc(){
    on.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(turnOn,0);
            Message.message(MainActivity.this , "Bluetooth enabled");
        }
    });
    off.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            adapter.disable();
        }
    });
    pairedDevice.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        lista(1);
        }
    });
    discoverable.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent discoverableIntent = new
                    Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 1);
            startActivity(discoverableIntent);
        }
    });
    nearDevices.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            lista(0);
        }
    });
}



public void find(){
    IntentFilter filter = new IntentFilter();

    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

    registerReceiver(mReceiver, filter);
    adapter.startDiscovery();
}

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
            //discovery starts, we can show progress dialog or perform other tasks
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            //discovery finishes, dismis progress dialog
        } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            //bluetooth device found
            BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            discoveredDevices.add(device);
            Message.message(MainActivity.this, "Found device " + device.getName());
            lista(0);
        }
    }
};






public void initialize(){
    on = (Button) findViewById(R.id.ON);
    off = (Button) findViewById(R.id.OFF);
    pairedDevice = (Button) findViewById(R.id.pairedDevices);
    nearDevices = (Button) findViewById(R.id.nearDevices);
    discoverable = (Button) findViewById(R.id.makeDiscoverable);
    lv = (ListView) findViewById(R.id.listaUredjaja);
    adapter = BluetoothAdapter.getDefaultAdapter();
    if(adapter == null){
        System.out.close();
    }
    if(adapter.isEnabled()){
        Message.message(MainActivity.this , "Enabled");
    }
    else{
        Message.message(MainActivity.this , "Not enabled");
    }
}

}

这是我的电脑上等待连接的服务器:

public class Mejn {

//start server
private void startServer() throws IOException{

    //Create a UUID for SPP
    UUID uuid = new UUID("1101", true);
    //Create the servicve url
    String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";

    //open server url
    StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );

    //Wait for client connection
    System.out.println("\nServer Started. Waiting for clients to connect...");
    StreamConnection connection=streamConnNotifier.acceptAndOpen();

    RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
    System.out.println("Remote device address: "+dev.getBluetoothAddress());
    System.out.println("Remote device name: "+dev.getFriendlyName(true));

    //read string from spp client
    InputStream inStream=connection.openInputStream();
    BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
    String lineRead=bReader.readLine();
    System.out.println(lineRead);

    //send response to spp client
    OutputStream outStream=connection.openOutputStream();
    PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
    pWriter.write("Response String from SPP Server\r\n");
    pWriter.flush();

    pWriter.close();
    streamConnNotifier.close();

}


public static void main(String[] args) throws IOException {

    //display local device address and name
    LocalDevice localDevice = LocalDevice.getLocalDevice();
    System.out.println("Address: "+localDevice.getBluetoothAddress());
    System.out.println("Name: "+localDevice.getFriendlyName());

    Mejn sampleSPPServer=new Mejn();
    sampleSPPServer.startServer();

}

}

1 个答案:

答案 0 :(得分:0)

所以,在查看更多信息的同时,在某处找到并将其放入我的代码中,以下是代码:

public class MainActivity extends Activity {
private BluetoothAdapter adapter;
private Intent turnOn;
private Set<BluetoothDevice> pairedDevices;
private ListView lv;
private Button on,off,pairedDevice,discoverable,nearDevices;
private List<BluetoothDevice> discoveredDevices = new ArrayList<BluetoothDevice>();
private BluetoothSocket btSocket = null;
public OutputStream outStream;
private static final UUID MY_UUID =
        UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String address = "C01885BD823C";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initialize();
    buttonFunc();
    find();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}



public void lista(int i){
    if(i==0) {
        final DeviceAdapter deviceAdapter = new DeviceAdapter(MainActivity.this, discoveredDevices);
        lv.setAdapter(deviceAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                pairDevice(deviceAdapter.getItem(position));
                Message.message(MainActivity.this, deviceAdapter.getItem(position).getName().toString());
            }
        });
    }
    else if(i == 1){
        List<BluetoothDevice> vecUpareni = new ArrayList<BluetoothDevice>();

        for (BluetoothDevice bt:adapter.getBondedDevices()){
            vecUpareni.add(bt);
        }
        final DeviceAdapter deviceAdapter = new DeviceAdapter(MainActivity.this,  vecUpareni);
        lv.setAdapter(deviceAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device = adapter.getRemoteDevice(deviceAdapter.getItem(position).getAddress());
                try {
                    btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
                } catch (IOException e) {
                    Message.message(MainActivity.this , "In onResume() and socket create failed: " + e.toString() + ".");
                }
                adapter.cancelDiscovery();
                try {
                    btSocket.connect();
                    System.out.print("\n...Connection established and data link opened...");
                } catch (IOException e) {
                    try {
                        btSocket.close();
                    } catch (IOException e2) {
                        Message.message(MainActivity.this , "In onResume() and unable to close socket during connection failure" + e2.getMessage().toString() + ".");
                    }
                }
                try {
                    outStream = btSocket.getOutputStream();
                } catch (IOException e) {
                    Message.message(MainActivity.this , "In onResume() and output stream creation failed:" + e.getMessage() + ".");
                }
                System.out.print("\n...Sending message to server...");
                String message = "Hello from Android.\n";
                System.out.print("\n\n...The message that we will send to the server is: "+message);
                byte[] msgBuffer = message.getBytes();
                try {
                    outStream.write(message.getBytes());
                } catch (IOException e) {
                    String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
                    if (address.equals("00:00:00:00:00:00"))
                        msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
                    msg = msg +  ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";

                    Message.message(MainActivity.this , msg);
                }



            }
        });
    }
}


private Method getConnectMethod () {
    try {
        return BluetoothA2dp.class.getDeclaredMethod("connect", BluetoothDevice.class);
    } catch (NoSuchMethodException ex) {
        Message.message(MainActivity.this , "Unable to connect");
        return null;
    }
}


private void pairDevice(BluetoothDevice device) {
    try {
        Log.d("pairDevice()", "Start Pairing...");
        Method m = device.getClass().getMethod("createBond", (Class[]) null);
        m.invoke(device, (Object[]) null);
        Log.d("pairDevice()", "Pairing finished.");
    } catch (Exception e) {
        Log.e("pairDevice()", e.getMessage());
    }
}

public void buttonFunc(){
    on.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(turnOn,0);
            Message.message(MainActivity.this , "Bluetooth enabled");
        }
    });
    off.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            adapter.disable();
        }
    });
    pairedDevice.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        lista(1);
        }
    });
    discoverable.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent discoverableIntent = new
                    Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 1);
            startActivity(discoverableIntent);
        }
    });
    nearDevices.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            lista(0);
        }
    });
}



public void find(){
    IntentFilter filter = new IntentFilter();

    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

    registerReceiver(mReceiver, filter);
    adapter.startDiscovery();
}

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
            //discovery starts, we can show progress dialog or perform other tasks
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            //discovery finishes, dismis progress dialog
        } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            //bluetooth device found
            BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            discoveredDevices.add(device);
            Message.message(MainActivity.this, "Found device " + device.getName());
            lista(0);
        }
    }
};






public void initialize(){
    on = (Button) findViewById(R.id.ON);
    off = (Button) findViewById(R.id.OFF);
    pairedDevice = (Button) findViewById(R.id.pairedDevices);
    nearDevices = (Button) findViewById(R.id.nearDevices);
    discoverable = (Button) findViewById(R.id.makeDiscoverable);
    lv = (ListView) findViewById(R.id.listaUredjaja);
    adapter = BluetoothAdapter.getDefaultAdapter();
    if(adapter == null){
        System.out.close();
    }
    if(adapter.isEnabled()){
        Message.message(MainActivity.this , "Enabled");
    }
    else{
        Message.message(MainActivity.this , "Not enabled");
    }
}

}

服务器的代码:

/ ** *实现接受单行的SPP服务器的类 *来自SPP客户端的消息,并向客户端发送一行响应。 * / 公共课Mejn {

//start server
private void startServer() throws IOException{

    //Create a UUID for SPP
    UUID uuid = new UUID("1101", true);
    //Create the servicve url
    String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";

    //open server url
    StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );

    //Wait for client connection
    System.out.println("\nServer Started. Waiting for clients to connect...");
    StreamConnection connection=streamConnNotifier.acceptAndOpen();

    RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
    System.out.println("Remote device address: "+dev.getBluetoothAddress());
    System.out.println("Remote device name: "+dev.getFriendlyName(true));

    //read string from spp client
    InputStream inStream=connection.openInputStream();
    BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
    String lineRead=bReader.readLine();
    System.out.println(lineRead);

    //send response to spp client
    OutputStream outStream=connection.openOutputStream();
    PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
    pWriter.write("Response String from SPP Server\r\n");
    pWriter.flush();

    pWriter.close();

    streamConnNotifier.close();

}


public static void main(String[] args) throws IOException {

    //display local device address and name
    LocalDevice localDevice = LocalDevice.getLocalDevice();
    System.out.println("Address: "+localDevice.getBluetoothAddress());
    System.out.println("Name: "+localDevice.getFriendlyName());

    Mejn sampleSPPServer=new Mejn();
    sampleSPPServer.startServer();

}

}