2015-04-01 210 views
0

所以,我想我的應用程序連接到我的電腦,然後使用android作爲觸摸板。我一直在網上做了大量的研究,但我沒有找到任何地方如何將我的手機精確連接到PC。我做了配對設備功能和其他一切,我只需要連接方法,或者至少可以做到這一點。下面是代碼:將藍牙從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(); 

} 

}

回答

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

} 

}