2016-05-08 9 views
0

Hallo Ich möchte eine einfache Nachricht an ein anderes Gerät per Bluetooth senden. Einfaches "a", das in textView auf einem anderen Gerät erscheint.So senden Sie eine Nachricht an das gekoppelte Gerät per Bluetooth

Ich habe es geschafft, Geräte zu koppeln, aber jetzt habe ich nur ein Problem, wie man eine Nachricht oder sogar Variable an ein anderes Gerät sendet, indem man auf die Schaltfläche klickt.

Das ist meine Klasse, die für die Verbindung verantwortlich ist

public class DeviceListActivity extends Activity { 


    private static final UUID MY_UUID_SECURE = 
      UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"); 
    private static final UUID MY_UUID_INSECURE = 
      UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"); 
    // private ConnectThread mConnectThread; 
    private int mState; 

    public static final int MESSAGE_STATE_CHANGE = 1; 
    public static final int MESSAGE_READ = 2; 
    public static final int MESSAGE_WRITE = 3; 
    public static final int MESSAGE_DEVICE_NAME = 4; 
    public static final int MESSAGE_TOAST = 5; 

    public static final String DEVICE_NAME = "device_name"; 
    public static final String TOAST = "toast"; 
    // private ConnectedThread mConnectedThread; 
    // Constants that indicate the current connection state 
    public static final int STATE_NONE = 0;  // we're doing nothing 
    public static final int STATE_LISTEN = 1;  // now listening for incoming connections 
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection 
    public static final int STATE_CONNECTED = 3; // now connected to a remote device 
    private String mConnectedDeviceName = null; 
    private ArrayAdapter<String> mConversationArrayAdapter; 
    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1; 
    private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2; 
    private static final int REQUEST_ENABLE_BT = 3; 
    ListView listViewPaired; 
    ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices; 
    ArrayList<String> arrayListpaired; 
    ArrayAdapter<String> adapter,detectedAdapter; 
    BluetoothDevice bdDevice; 
    ArrayList<BluetoothDevice> arrayListBluetoothDevices = null; 
    ListItemClicked listItemClicked; 
    ListView newDevicesListView; 


    private static final String TAG = "DeviceListActivity"; 
    //making btAdapter and ArrayAdapter 
    private BluetoothAdapter mBtAdapter; 
    private ArrayAdapter<String> mNewDevicesArrayAdapter; 
    public static String EXTRA_DEVICE_ADDRESS = "device_address"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_device_list); 

     mBtAdapter = BluetoothAdapter.getDefaultAdapter(); 

     // onclicklistener for discovering devices 
     Button scanButton = (Button) findViewById(R.id.scan); 
     scanButton.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       doDiscovery(); 
       v.setVisibility(View.GONE); 
      } 
     }); 


     // FOR DISCOVERY 

     mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice); 
     // Find and set up the ListView for newly discovered devices 
     newDevicesListView = (ListView) findViewById(R.id.new_devices); 
     newDevicesListView.setAdapter(mNewDevicesArrayAdapter); 
     /////////////////newDevicesListView.setOnItemClickListener(mDeviceClickListener); 
     // Register for broadcasts when a device is discovered 
     IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
     DeviceListActivity.this.registerReceiver(mReceiver, filter); 
     // Register for broadcasts when discovery has finished 
     filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 
     DeviceListActivity.this.registerReceiver(mReceiver, filter); 

     // FOR PAIRED 
     ArrayAdapter<String> pairedDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); 
     ListView pairedListView = (ListView) findViewById(R.id.paired_devices); 
     pairedListView.setAdapter(pairedDevicesArrayAdapter); 
     ////////////////////////pairedListView.setOnItemClickListener(mDeviceClickListener); 
     Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices(); 

     // If there are paired devices, add each one to the ArrayAdapter 
     if (pairedDevices.size() > 0) { 
      findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); 
      for (BluetoothDevice device : pairedDevices) { 
       pairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
      } 
     } else { 
      String noDevices = getResources().getText(R.string.none_paired).toString(); 
      pairedDevicesArrayAdapter.add(noDevices); 
     } 





     arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>(); 
     arrayListpaired = new ArrayList<String>(); 
     arrayListBluetoothDevices = new ArrayList<BluetoothDevice>(); 
     adapter= new ArrayAdapter<String>(DeviceListActivity.this, android.R.layout.simple_list_item_1, arrayListpaired); 
     listItemClicked = new ListItemClicked(); 


} 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     // Unregister broadcast listeners 
     this.unregisterReceiver(mReceiver); 
    } 


    private void doDiscovery() { 
     Log.d(TAG, "doDiscovery()"); 

     // Indicate scanning in the title 
     setProgressBarIndeterminateVisibility(true); 
     setTitle(R.string.scanning); 

     // Turn on sub-title for new devices 
     findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE); 

     // Request discover from BluetoothAdapter 
     mBtAdapter.startDiscovery(); 
    } 

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

      // When discovery finds a device 
      if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
       // Get the BluetoothDevice object from the Intent 
       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       // If it's already paired, skip it, because it's been listed already 
       if (device.getBondState() != BluetoothDevice.BOND_BONDED) { 
        mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
        arrayListBluetoothDevices.add(device); 
        mNewDevicesArrayAdapter.notifyDataSetChanged(); 
       } 
       if(arrayListBluetoothDevices.size()<1) // this checks if the size of bluetooth device is 0,then add the 
       {           // device to the arraylist. 
        arrayListBluetoothDevices.add(device); 
        mNewDevicesArrayAdapter.notifyDataSetChanged(); 
       } 

       // When discovery is finished, change the Activity title 
      } 



      else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 
       setProgressBarIndeterminateVisibility(false); 
       setTitle(R.string.select_device); 
       if (mNewDevicesArrayAdapter.getCount() == 0) { 
        String noDevices = getResources().getText(R.string.none_found).toString(); 
        mNewDevicesArrayAdapter.add(noDevices); 
       } 
      } 
     } 
    }; 

class ListItemClicked implements AdapterView.OnItemClickListener 
{ 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
     // TODO Auto-generated method stub 
     bdDevice = arrayListBluetoothDevices.get(position); 
     //bdClass = arrayListBluetoothDevices.get(position); 
     Log.i("Log", "The dvice : "+bdDevice.toString()); 
      /* 
      * here below we can do pairing without calling the callthread(), we can directly call the 
      * connect(). but for the safer side we must usethe threading object. 
      */ 
     //callThread(); 
     //connect(bdDevice); 
     Boolean isBonded = false; 
     try { 
      isBonded = createBond(bdDevice); 
      if(isBonded) 
      { 
       //arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress()); 
       //adapter.notifyDataSetChanged(); 
       getPairedDevices(); 
       adapter.notifyDataSetChanged(); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     }//connect(bdDevice); 
     Log.i("Log", "The bond is created: "+isBonded); 
    } 
} 


    public boolean createBond(BluetoothDevice btDevice) 
      throws Exception 
    { 
     Class class1 = Class.forName("android.bluetooth.BluetoothDevice"); 
     Method createBondMethod = class1.getMethod("createBond"); 
     Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice); 
     return returnValue.booleanValue(); 
    } 


    private void getPairedDevices() { 
     Set<BluetoothDevice> pairedDevice = mBtAdapter.getBondedDevices(); 
     if(pairedDevice.size()>0) 
     { 
      for(BluetoothDevice device : pairedDevice) 
      { 
       arrayListpaired.add(device.getName()+"\n"+device.getAddress()); 
       arrayListPairedBluetoothDevices.add(device); 
      } 
     } 
     adapter.notifyDataSetChanged(); 
    } 

    @Override 
    protected void onStart() { 
     // TODO Auto-generated method stub 
     super.onStart(); 
     getPairedDevices(); 
     newDevicesListView.setOnItemClickListener(listItemClicked); 
    } 

} 

Das ist mein XML-Datei

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 


     <Button 
      android:id="@+id/button_send" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="@string/send" 
      android:layout_gravity="center_horizontal" 
      android:layout_alignParentBottom="true" 
      android:layout_centerHorizontal="true" 
      android:layout_marginBottom="69dp" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="New Text" 
     android:id="@+id/textView" 
     android:layout_above="@+id/button_send" 
     android:layout_centerHorizontal="true" 
     android:layout_marginBottom="200dp" /> 


</RelativeLayout> 
+0

Sie haben dieselbe Frage mehrmals gestellt. Bitte nicht umbuchen. –

Antwort

1

Aber wenn Sie eine Bluetooth-Anwendung erstellen möchten, sollten Sie grundlegende Konzepte verstehen. Hast du this Theorie über Bluetooth API gelesen?

Dann schauen Sie sich this android Beispielprojekt. Analysieren Sie den Code in BluetoothChatService.java Klasse.

Am Ende der BluetoothChatService.java Klasse sollten Sie 3 Threads Klassen bemerken. Wenn die Anwendung gestartet wird, fungieren beide Android-Geräte als Server, sodass sie auf eine eingehende Verbindung warten (Socket). Auf beiden Geräten läuft der Thread AcceptThread und wartet auf die Verbindung. Dann beschließt einer von ihnen sich mit einem anderen zu verbinden, so dass es ConnectThread Thread startet. Dort senden Sie Ihre Socket an den Server. Also auf einem Gerät Server fängt diese Socket in AcceptThread und auf einem anderen Gerät erhalten Sie diese Socket in ConnectThread verbunden. Jetzt starten Sie auf beiden Geräten mit angeschlossenem Socket. Dort erhalten Sie einfach InputStream und OutputStream, um Bytes zu erhalten bzw. Bytes zu senden. Dann in endlosen while Schleife Sie warten auf eingehende Bytes und senden Bytes mit public void write(byte[] buffer) Methode Ihrer BluetoothChatService Objekt.

+0

Ich habe versucht, dieses Beispiel in meinem Programm zu verwenden, aber es ist zu kompliziert. Ich weiß nicht, welche Methoden ich verwenden sollte, um dieses Problem zu lösen. –

+0

Aber wenn Sie eine Bluetooth-Anwendung erstellen möchten, sollten Sie grundlegende Konzepte verstehen. Hast du [this] (http://developer.android.com/guide/topics/connectivity/bluetooth.html) Theorie über Bluetooth API gelesen? – Tinko

+0

Ja, mehrmals. Ich habe bereits Geräte gepaart, die Sache ist, ich würde gerne eine Stringvariable durch Drücken auf den Button senden. Diese Variable sollte in TextView auf einem anderen Gerät angezeigt werden. Ich bin neu in Android, ich habe diese ConnectThread und ConnectedThreads, aber es hat nichts geändert –

0

Ok, ich habe etwas herausgefunden. Mein Chat funktioniert auf beiden Geräten, aber nach dem Klicken auf die Schaltfläche SENDEN wird nichts auf dem zweiten Gerät angezeigt. Danke für die Beschreibung :)

import android.app.ActionBar; 
import android.app.Activity; 

import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.bluetooth.BluetoothServerSocket; 
import android.bluetooth.BluetoothSocket; 
import android.content.Intent; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.support.annotation.Nullable; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.Snackbar; 
import android.support.v4.app.FragmentActivity; 
import android.support.v4.app.FragmentHostCallback; 
import android.support.v4.app.FragmentTransaction; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.support.v4.app.Fragment; 
import android.util.Log; 
import android.view.KeyEvent; 
import android.view.View; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.inputmethod.EditorInfo; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ListView; 
import android.widget.TextView; 
import android.widget.Toast; 

import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.UUID; 

public class MainActivity extends AppCompatActivity { 

    private BluetoothAdapter mBluetoothAdapter; 
    private BluetoothSocket mmSocket; 
    private InputStream mmInStream; 
    private OutputStream mmOutStream; 
    //private ConnectedThread mConnectedThread; 
    private EditText mOutEditText; 
    private StringBuffer mOutStringBuffer; 
    private static final String TAG = "MainActivity"; 
    private Button mSendButton; 
    private ArrayAdapter<String> mConversationArrayAdapter; 
    String tag = "debugging"; 
    private ListView mConversationView; 
    protected static final int SUCCESS_CONNECT = 0; 
    protected static final int MESSAGE_READ = 1; 
    // Unique UUID for this application 
    private static final UUID MY_UUID_SECURE = 
      UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"); 
    private static final UUID MY_UUID_INSECURE = 
      UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"); 
    private ConnectedThread mConnectedThread; 
    private int mState; 
    private static final String NAME_SECURE = "BluetoothChatSecure"; 
    private static final String NAME_INSECURE = "BluetoothChatInsecure"; 

    // Constants that indicate the current connection state 
    public static final int STATE_NONE = 0;  // we're doing nothing 
    public static final int STATE_LISTEN = 1;  // now listening for incoming connections 
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection 
    public static final int STATE_CONNECTED = 3; // now connected to a remote device 




    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     // variables 
     mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
     mConversationView = (ListView) findViewById(R.id.in); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     mOutEditText = (EditText) findViewById(R.id.edit_text_out); 
     mSendButton = (Button) findViewById(R.id.button_send); 
     mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.content_main); 

    } 

    @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. 
     switch (item.getItemId()) { 
      case R.id.discoverable: 
       ensureDiscoverable(); 
       return true; 
      case R.id.secure_connect_scan: 
       Intent intent = new Intent(this, DeviceListActivity.class); 
       startActivity(intent); 
       return true; 
      case R.id.disconnect: 
       mBluetoothAdapter.disable(); 
       return true; 
      default: 
       return super.onOptionsItemSelected(item); 

     } 
    } 

    private void ensureDiscoverable() { 
      Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 
      discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); 
      startActivity(discoverableIntent); 

    } 





    private class ConnectedThread extends Thread { 
     private final BluetoothSocket mmSocket; 
     private final InputStream mmInStream; 
     private final OutputStream mmOutStream; 

     public ConnectedThread(BluetoothSocket socket) { 
      mmSocket = socket; 
      InputStream tmpIn = null; 
      OutputStream tmpOut = null; 

      // Get the input and output streams, using temp objects because 
      // member streams are final 
      try { 
       tmpIn = socket.getInputStream(); 
       tmpOut = socket.getOutputStream(); 
      } catch (IOException e) { } 

      mmInStream = tmpIn; 
      mmOutStream = tmpOut; 
     } 

     public void run() { 
      byte[] buffer = new byte[1024]; // buffer store for the stream 
      int bytes; // bytes returned from read() 

      // Keep listening to the InputStream until an exception occurs 
      while (true) { 
       try { 
        // Read from the InputStream 
        bytes = mmInStream.read(buffer); 
        // Send the obtained bytes to the UI activity 
        mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) 
          .sendToTarget(); 
       } catch (IOException e) { 
        break; 
       } 
      } 
     } 

     /* Call this from the main activity to send data to the remote device */ 
     public void write(byte[] bytes) { 
      try { 
       mmOutStream.write(bytes); 
      } catch (IOException e) { } 
     } 

     /* Call this from the main activity to shutdown the connection */ 
     public void cancel() { 
      try { 
       mmSocket.close(); 
      } catch (IOException e) { } 
     } 
    } 


    Handler mHandler = new Handler(){ 
     @Override 
     public void handleMessage(Message msg) { 
      // TODO Auto-generated method stub 
      Log.i(tag, "in handler"); 
      super.handleMessage(msg); 
      switch(msg.what){ 
       case SUCCESS_CONNECT: 
        // DO something 
        ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj); 
        Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_SHORT).show(); 
        String s = "successfully connected"; 
        connectedThread.write(s.getBytes()); 
        Log.i(tag, "connected"); 
        break; 
       case MESSAGE_READ: 
        byte[] readBuf = (byte[])msg.obj; 
        String string = new String(readBuf); 
        Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show(); 
        break; 
      } 
     } 
    }; 


    public void write(byte[] out) { 
     // Create temporary object 
     ConnectedThread r; 
     // Synchronize a copy of the ConnectedThread 
     synchronized (this) { 
      if (mState != STATE_CONNECTED) return; 
      r = mConnectedThread; 
     } 
     // Perform the write unsynchronized 
     r.write(out); 
    } 

    private void sendMessage(String message) { 
     // Check that we're actually connected before trying anything 

     // Check that there's actually something to send 
     if (message.length() > 0) { 
      // Get the message bytes and tell the BluetoothChatService to write 
      // byte[] send = message.getBytes(); 
      // mChatService.write(send); 

      String messagess="blabla"; 
      byte[] send = messagess.getBytes(); 
      write(send); 

      // Reset out string buffer to zero and clear the edit text field 
      mOutStringBuffer.setLength(0); 
      mOutEditText.setText(mOutStringBuffer); 
     } 
    } 


    private void setupChat() { 
     Log.d(TAG, "setupChat()"); 

     // Initialize the array adapter for the conversation thread 
     mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.content_main); 

     mConversationView.setAdapter(mConversationArrayAdapter); 

     // Initialize the compose field with a listener for the return key 
    // mOutEditText.setOnEditorActionListener(mWriteListener); 

     // Initialize the send button with a listener that for click events 
     mSendButton.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       // Send a message using content of the edit text widget 


        TextView textView = (TextView) findViewById(R.id.edit_text_out); 
        String message = textView.getText().toString(); 
        sendMessage(message); 

      } 
     }); 


     // Initialize the buffer for outgoing messages 
     mOutStringBuffer = new StringBuffer(""); 
    } 


/* private TextView.OnEditorActionListener mWriteListener 
      = new TextView.OnEditorActionListener() { 
     public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { 
      // If the action is a key-up event on the return key, send the message 
      if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) { 
       String message = view.getText().toString(); 
       sendMessage(message); 
      } 
      return true; 
     } 
    };*/ 


    private class AcceptThread extends Thread { 
     // The local server socket 
     private final BluetoothServerSocket mmServerSocket; 
     private String mSocketType; 

     public AcceptThread(boolean secure) { 
      BluetoothServerSocket tmp = null; 
      mSocketType = secure ? "Secure" : "Insecure"; 

      // Create a new listening server socket 
      try { 
       if (secure) { 
        tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, 
          MY_UUID_SECURE); 
       } else { 
        tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(
          NAME_INSECURE, MY_UUID_INSECURE); 
       } 
      } catch (IOException e) { 
       Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e); 
      } 
      mmServerSocket = tmp; 
     } 

     public void run() { 
      Log.d(TAG, "Socket Type: " + mSocketType + 
        "BEGIN mAcceptThread" + this); 
      setName("AcceptThread" + mSocketType); 

      BluetoothSocket socket = null; 

      // Listen to the server socket if we're not connected 
      while (mState != STATE_CONNECTED) { 
       try { 
        // This is a blocking call and will only return on a 
        // successful connection or an exception 
        socket = mmServerSocket.accept(); 
       } catch (IOException e) { 
        Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e); 
        break; 
       } 

       // If a connection was accepted 
       if (socket != null) { 
        synchronized (this) { 
         switch (mState) { 
          case STATE_LISTEN: 
          case STATE_CONNECTING: 
           // Situation normal. Start the connected thread. 
           // connected(socket, socket.getRemoteDevice(), 
           //  mSocketType); 
           break; 
          case STATE_NONE: 
          case STATE_CONNECTED: 
           // Either not ready or already connected. Terminate new socket. 
           try { 
            socket.close(); 
           } catch (IOException e) { 
            Log.e(TAG, "Could not close unwanted socket", e); 
           } 
           break; 
         } 
        } 
       } 
      } 
      Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType); 

     } 

     public void cancel() { 
      Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this); 
      try { 
       mmServerSocket.close(); 
      } catch (IOException e) { 
       Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e); 
      } 
     } 
    } 



    @Override 
    public void onStart() { 
     super.onStart(); 
     // If BT is not on, request that it be enabled. 
     // setupChat() will then be called during onActivityResult 
     /* if (!mBluetoothAdapter.isEnabled()) { 
      Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      // Otherwise, setup the chat session 
     }*/ 
      setupChat(); 

    } 







} 
+0

Und wo verbinden Sie sich mit dem Gerät? Sie haben die Server-Seite implementiert, aber nicht den Host, wenn Sie eine Verbindung herstellen, also warten Sie auf die Verbindung, aber erstellen Sie keine ... Sehen Sie sich die 'ConnectThread'-Klasse in' BluetoothChatService' an – Tinko

0

Aber diese Geräte sind bereits gepaart, oder bekomme ich es falsch.

Hier ist eine Klasse, die für die Verbindung und dann für die Paarung von Geräten zuständig ist.

public class DeviceListActivity extends Activity { 

    ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices; 
    ArrayList<String> arrayListpaired; 
    ArrayAdapter<String> adapter,detectedAdapter; 
    BluetoothDevice bdDevice; 
    ArrayList<BluetoothDevice> arrayListBluetoothDevices = null; 
    ListItemClicked listItemClicked; 
    ListView newDevicesListView; 


    private static final String TAG = "DeviceListActivity"; 
    //making btAdapter and ArrayAdapter 
    private BluetoothAdapter mBtAdapter; 
    private ArrayAdapter<String> mNewDevicesArrayAdapter; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_device_list); 

     mBtAdapter = BluetoothAdapter.getDefaultAdapter(); 

     // onclicklistener for discovering devices 
     Button scanButton = (Button) findViewById(R.id.scan); 
     scanButton.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       doDiscovery(); 
       v.setVisibility(View.GONE); 
      } 
     }); 


     // FOR DISCOVERY 

     mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice); 
     // Find and set up the ListView for newly discovered devices 
     newDevicesListView = (ListView) findViewById(R.id.new_devices); 
     newDevicesListView.setAdapter(mNewDevicesArrayAdapter); 
     /////////////////newDevicesListView.setOnItemClickListener(mDeviceClickListener); 
     // Register for broadcasts when a device is discovered 
     IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
     DeviceListActivity.this.registerReceiver(mReceiver, filter); 
     // Register for broadcasts when discovery has finished 
     filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 
     DeviceListActivity.this.registerReceiver(mReceiver, filter); 

     // FOR PAIRED 
     ArrayAdapter<String> pairedDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); 
     ListView pairedListView = (ListView) findViewById(R.id.paired_devices); 
     pairedListView.setAdapter(pairedDevicesArrayAdapter); 
     ////////////////////////pairedListView.setOnItemClickListener(mDeviceClickListener); 
     Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices(); 

     // If there are paired devices, add each one to the ArrayAdapter 
     if (pairedDevices.size() > 0) { 
      findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); 
      for (BluetoothDevice device : pairedDevices) { 
       pairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
      } 
     } else { 
      String noDevices = getResources().getText(R.string.none_paired).toString(); 
      pairedDevicesArrayAdapter.add(noDevices); 
     } 





     arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>(); 
     arrayListpaired = new ArrayList<String>(); 
     arrayListBluetoothDevices = new ArrayList<BluetoothDevice>(); 
     adapter= new ArrayAdapter<String>(DeviceListActivity.this, android.R.layout.simple_list_item_1, arrayListpaired); 
     listItemClicked = new ListItemClicked(); 


    } 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     // Unregister broadcast listeners 
     this.unregisterReceiver(mReceiver); 
    } 


    private void doDiscovery() { 
     Log.d(TAG, "doDiscovery()"); 

     // Indicate scanning in the title 
     setProgressBarIndeterminateVisibility(true); 
     setTitle(R.string.scanning); 

     // Turn on sub-title for new devices 
     findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE); 

     // Request discover from BluetoothAdapter 
     mBtAdapter.startDiscovery(); 
    } 

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

      // When discovery finds a device 
      if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
       // Get the BluetoothDevice object from the Intent 
       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       // If it's already paired, skip it, because it's been listed already 
       if (device.getBondState() != BluetoothDevice.BOND_BONDED) { 
        mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
        arrayListBluetoothDevices.add(device); 
        mNewDevicesArrayAdapter.notifyDataSetChanged(); 
       } 
       if(arrayListBluetoothDevices.size()<1) // this checks if the size of bluetooth device is 0,then add the 
       {           // device to the arraylist. 
        arrayListBluetoothDevices.add(device); 
        mNewDevicesArrayAdapter.notifyDataSetChanged(); 
       } 

       // When discovery is finished, change the Activity title 
      } 



      else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 
       setProgressBarIndeterminateVisibility(false); 
       setTitle(R.string.select_device); 
       if (mNewDevicesArrayAdapter.getCount() == 0) { 
        String noDevices = getResources().getText(R.string.none_found).toString(); 
        mNewDevicesArrayAdapter.add(noDevices); 
       } 
      } 
     } 
    }; 

    class ListItemClicked implements AdapterView.OnItemClickListener 
    { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      // TODO Auto-generated method stub 
      bdDevice = arrayListBluetoothDevices.get(position); 
      //bdClass = arrayListBluetoothDevices.get(position); 
      Log.i("Log", "The dvice : "+bdDevice.toString()); 
      /* 
      * here below we can do pairing without calling the callthread(), we can directly call the 
      * connect(). but for the safer side we must usethe threading object. 
      */ 
      //callThread(); 
      //connect(bdDevice); 
      Boolean isBonded = false; 
      try { 
       isBonded = createBond(bdDevice); 
       if(isBonded) 
       { 
        //arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress()); 
        //adapter.notifyDataSetChanged(); 
        getPairedDevices(); 
        adapter.notifyDataSetChanged(); 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      }//connect(bdDevice); 
      Log.i("Log", "The bond is created: "+isBonded); 
     } 
    } 


    public boolean createBond(BluetoothDevice btDevice) 
      throws Exception 
    { 
     Class class1 = Class.forName("android.bluetooth.BluetoothDevice"); 
     Method createBondMethod = class1.getMethod("createBond"); 
     Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice); 
     return returnValue.booleanValue(); 
    } 


    private void getPairedDevices() { 
     Set<BluetoothDevice> pairedDevice = mBtAdapter.getBondedDevices(); 
     if(pairedDevice.size()>0) 
     { 
      for(BluetoothDevice device : pairedDevice) 
      { 
       arrayListpaired.add(device.getName()+"\n"+device.getAddress()); 
       arrayListPairedBluetoothDevices.add(device); 
      } 
     } 
     adapter.notifyDataSetChanged(); 
    } 

    @Override 
    protected void onStart() { 
     // TODO Auto-generated method stub 
     super.onStart(); 
     getPairedDevices(); 
     newDevicesListView.setOnItemClickListener(listItemClicked); 
    } 

} 
Verwandte Themen