Bluetooth verbindung

  • 15 Antworten
  • Letztes Antwortdatum
S

Schütz12

Neues Mitglied
0
Hallo Leute

Ich versuche nun schon lange eine Verbindung mit einem Bluetooth Gerät hinzubekommen. Leider scheitert es bei mir bei dieser Funktion:

bluetoothSocket.connect();

Bei dieser Zeile bricht das Programm zwar nicht ab aber es macht den ProgrammCode nicht weiter.

Hier das Programm:

btDevice = mbluetoothdevice.get(i);
BluetoothSocket bluetoothSocket=null;

try {
bluetoothSocket = btDevice.createRfcommSocketToServiceRecord(
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));

} catch (IOException e) {
// handle exception
}
bluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception

bluetoothSocket.connect();
begin.setText("Connect with "+btDevice);
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
bluetoothSocket.close();
} catch (IOException closeException) {
// handle exception
}
}


Was könnte hier der Fehler sein?

Danke für Antworten

Der ursprüngliche Beitrag von 16:55 Uhr wurde um 16:55 Uhr ergänzt:

Ich bekomme halt keine Verbindung zusammen und es muss an den letzten try-catch Block liegen
 
Abend,

mein Eindruck ist gerade folgender:
Die App versucht eine Verbindung mit dem Gerät aufzubauen - und versucht dies...eine Weile.
In deinem Fall heißt es ewig, bis du die App beendest, dein Handy aus Frust im Klo runterspülst oder einfach lange genug das du bis dato aufgegeben und die App beendet hast[was ich aber nicht glaube, ich spekuliere auf eine der ersten 3 Optionen], jedenfalls so lange das gar keine Exception ausgeworfen wird, denn er versucht ja weiter zu verbinden(man siehe auch: Sockets-->Timeouts).
 
Also meinst du das die verbindung aufzubauen solange dauert?

Ist das normal oder kann man dies irgendwie beschleunigen?
 
nein, ich denke die Verbindung kann nicht aufgebaut werden, nur versucht er es weiter bis der Timeout erreicht ist, also...nie.
Du könntest ja mal einen Timeout > 0 setzen und schauen was passiert;)
 
Und jetzt ist nur noch die frage warum kann keine verbindung aufgebaut werden kann?

Und was ich ändern muss..

Der ursprüngliche Beitrag von 22:49 Uhr wurde um 22:51 Uhr ergänzt:

Und jetzt ist nur noch die frage warum kann keine verbindung aufgebaut werden kann?

Und was ich ändern muss..

Der ursprüngliche Beitrag von 22:51 Uhr wurde um 22:54 Uhr ergänzt:

Und jetzt ist nur noch die frage warum kann keine verbindung aufgebaut werden kann?

Und was ich ändern muss..
 
checke mal deine Methode die Devices zu holen - vielleicht ist das ja ein Problem. Ansonsten müsste ich an der Stelle dann passen.
 
Oke ich werde mal die methode ändern und schaun ob es dann funktioniert, werde mich dann melden :)
 
Also ich bin am verzweifeln, ich bekomme keine Verbindung zusammen.

Dies sind die Methoden die ich in einem AlertBuilder aufrufe.

------------------------------------------

ConnectThread(mbluetoothdevice.get(item));
run();

-----------------------------------------

ConnectThread(BluetoothDevice device):
-------------------------------------------------------------------
void ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
tmp = null;
mmDevice = device;

// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}

------------------------------------------------------------------------------

run():
----------------------------------------------------------------------------------
public void run() {
// Cancel discovery because it will slow down the connection
bluetoothAdapter.cancelDiscovery();

try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
begin.setText("connected");
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
begin.setText("Unable to connect");
} catch (IOException closeException) { }
return;
}
}
-----------------------------------------------------------------------------------------

Also der Fehler liegt noch immer bei mmSocket.connect();

Ich übergebe als Device etwas falsches sodass .connect() nichts damit anfangen kann, glaube ich einmal.

Aber ich habe alles schon durchprobiert und bin auf Hilfe angewiesen!

Wäre nett wenn ihr mir dabei helfen könntet!
 
Mach einfach mal eine Log Ausgabe vor dem connect und nach dem connect, sowie im catch Block. Wenn du nur bis zum connect kommst, dann hast du ein falsches Device, weil connect blocken sollte bis eine Verbindung zu stande kommt oder man close aufruft.

Wenn du vermutest das der Fehler am Device liegt, dann zeig doch mal den Code dafür oder stell direkt alles zur Verfügung, wenn du darfst. Zur Not mal createRfcommSocketToServiceRecord durch die Insecure Variante ersetzen und gucken, ob es da irgendwelche Probleme gibt.

P.S: Benutze bitte die Code Tags damit Quellcode vernünftig gelesen werden kann.
 
  • Danke
Reaktionen: Schütz12
Hier ist der BroadcastReceiver. Sobald ein Gerät gefunden wird wird es in einer ArrayList gefügt.

Code:
BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){

			  @Override
			  public void onReceive(Context context, Intent intent) {
			   // TODO Auto-generated method stub
			   String action = intent.getAction();
			   if(BluetoothDevice.ACTION_FOUND.equals(action)) {
			             BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			             mbluetoothdevice.add(device);
			             dialog();
			   }
			  }};

Danach wird die Methode dialog(); geöffnet:

Code:
void dialog(){
    	
   	 //final CharSequence[] items = listItems.toArray(new CharSequence[listItems.size()]);
			CharSequence[] items = new CharSequence[mbluetoothdevice.size()];
	
	// collect names of BT devices for the list
			for (int i = 0; i < items.length; i++) {
				items[i] = mbluetoothdevice.get(i).getName();
				}

  
   	AlertDialog.Builder builder = new AlertDialog.Builder(this);
       builder.setTitle("devices");
       builder.setItems(items, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int item) {
               // Do something with the selection
       
   
        	  ConnectThread(mbluetoothdevice.get(item));
        	  run();
    		
           }
       });
       AlertDialog alert = builder.create();
       alert.show();
   }

Das ist der Code den ich verwende um das Device das gefunden worden ist zu speichern, und danach wieder abzurufen welches Gerät ausgewählt werden soll.
 
Schütz12;7010179 schrieb:
Code:
        	  ConnectThread(mbluetoothdevice.get(item));
        	  run();
    		
[/quote]

Was machst du denn an der Stelle? Ohne den genauen Kontext sieht es falsch aus. "ConnectThread" sollte doch eigentlich sowas wie eine Klasse sein, wovon dir dann mit new ein Objekt erzeugst. Zumindest denke ich das, wenn du einen Methodennamen groß anfängst. Da dir aber so schon Syntaxfehler um die Ohren fliegen würden, ist das offenbar nur eine Methode in deiner Klasse, die einen Thread erweitert oder Runnable implementiert.

Gibt dir Logcat wirklich nichts aus? Das sieht so aus als ob du das aus dem UIThread aus aufrufst. Dann kann es nicht funktionieren und der Aufruf "run()" für einen Thread ist falsch. Ein Thread wird mir "start()" gestartet, dort wird automatisch in einem neuen Thread die "run" Methode ausgeführt.

Versuch es also mal mit start(); statt run(); und guck bitte mal ins Logcat, falls es immer noch nicht funktioniert.
 
Ich habe nun daraus eine Klasse gemacht in der sich ConnectThread(nun AcceptThread) darin befindet. run() ist auch eine Funktion in dieser Klasse und kein Aufruf von einem Thread!

Hier mein Programm:

Code:
public class MainActivity extends Activity implements OnClickListener,OnInitListener,OnTouchListener {
 	
	private static final int REQUEST_ENABLE_BT = 1;
	 
	 BluetoothAdapter bluetoothAdapter;
	 Context mContext;
	 List<String> listItems = new ArrayList<String>();
	 BluetoothDevice btDevice;
	 BluetoothSocket bluetoothSocket;
	 ArrayAdapter<String> btArrayAdapter;
	 ArrayList<BluetoothDevice>	mbluetoothdevice= new ArrayList<BluetoothDevice>();
	 BluetoothSocket mmSocket;
	 BluetoothDevice mmDevice;
	 BluetoothSocket tmp;
	
	
	
	
	private Button start;
	private Button cancel;
	private TextView begin;
	private TextView state;
	private TextToSpeech tts;
	private int x_touch;
	private int y_touch;
	public int starttimer;
	private TextView textcounter;
	private Handler handler = new Handler();
	private boolean delay;
	static UUID MY_UUID;
	private Runnable runnable=new Runnable(){
		
		private int counter=3;
		
		public void run() 
		{
			
			if(delay==true)
			{
				tts.speak(""+counter, TextToSpeech.QUEUE_FLUSH, null);
				textcounter.setText(""+counter);
				delay=false;
				handler.postDelayed(this, 1000);
			}else{
			
			tts.speak(""+counter, TextToSpeech.QUEUE_FLUSH, null);	
			textcounter.setText(""+counter);
			
			if(counter==0)
			{
				tts.speak(" Start ", TextToSpeech.QUEUE_FLUSH, null);
				setviewwischen();
				counter=3;
				return;
				
			}else{
				
			handler.postDelayed(this, 1000);
			
				}
			}
			counter--;
			
		}
		
	};
	
		
    
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        start = (Button)findViewById(R.id.startbutton);
        start.setOnClickListener(this);
        begin = (TextView)findViewById(R.id.TextView1);
        
        tts = new TextToSpeech(this,this);
        
        MY_UUID = UUID.randomUUID();
        
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        
        CheckBlueToothState();
        
        registerReceiver(ActionFoundReceiver, 
                new IntentFilter(BluetoothDevice.ACTION_FOUND));
        
        
        bluetoothAdapter.startDiscovery();
        
      
	} 
	
		void dialog(){
    	
   	 //final CharSequence[] items = listItems.toArray(new CharSequence[listItems.size()]);
			CharSequence[] items = new CharSequence[mbluetoothdevice.size()];
	
	// collect names of BT devices for the list
			for (int i = 0; i < items.length; i++) {
				items[i] = mbluetoothdevice.get(i).getName();
				}

  
   	AlertDialog.Builder builder = new AlertDialog.Builder(this);
       builder.setTitle("devices");
       builder.setItems(items, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int item) {
               // Do something with the selection
        	 
        	   AcceptThread connect = new AcceptThread(mbluetoothdevice.get(item));
        	   connect.run();
    		
           }
       });
       AlertDialog alert = builder.create();
       alert.show();
   }
		private class AcceptThread extends Thread {	
			
			AcceptThread(BluetoothDevice device) {
				// Use a temporary object that is later assigned to mmSocket,
				// because mmSocket is final
				tmp = null;
				mmDevice = device;
	 
				// Get a BluetoothSocket to connect with the given BluetoothDevice
				try {
					// MY_UUID is the app's UUID string, also used by the server code
					tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
				} catch (IOException e) { }
				mmSocket = tmp;
	    }
	 
	    public void run() {
	        // Cancel discovery because it will slow down the connection
	        bluetoothAdapter.cancelDiscovery();
	 
	        try {
	            // Connect the device through the socket. This will block
	            // until it succeeds or throws an exception
	            mmSocket.connect();
	            begin.setText("connected");
	        } catch (IOException connectException) {
	            // Unable to connect; close the socket and get out
	            try {
	                mmSocket.close();
	                begin.setText("Unable to connect");
	            } catch (IOException closeException) { }
	            return;
	        }
	    }
		}
	  
		
		 @Override
		protected void onDestroy() {
		  // TODO Auto-generated method stub
		  super.onDestroy();
		  unregisterReceiver(ActionFoundReceiver);
		 }

		 
		private void CheckBlueToothState(){
		     if (bluetoothAdapter == null){
		         begin.setText("Bluetooth NOT support");
		        }else{
		         if (bluetoothAdapter.isEnabled()){
		          if(bluetoothAdapter.isDiscovering()){
		           begin.setText("Bluetooth is currently in device discovery process.");
		          }else{
		           begin.setText("Bluetooth is Enabled.");
		          }
		         }else{
		          begin.setText("Bluetooth is NOT Enabled!");
		          Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		             startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		         }
		        }
		    }
		
		
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			  // TODO Auto-generated method stub
			  if(requestCode == REQUEST_ENABLE_BT){
			   CheckBlueToothState();
			  }
			 }

		
		BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){

			  @Override
			  public void onReceive(Context context, Intent intent) {
			   // TODO Auto-generated method stub
			   String action = intent.getAction();
			   if(BluetoothDevice.ACTION_FOUND.equals(action)) {
			             BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			             mbluetoothdevice.add(device);
			             dialog();
			   }
			  }};
		
			 
			 
			 
			 
	  
	  @Override
	    public void onClick(View v)
		{
			if(v.getId() == R.id.startbutton)
			{
				setContentView(R.layout.timer);
				textcounter=(TextView)findViewById(R.id.time);
				handler.postDelayed(runnable, 500);
				delay=true;
				
			
			    return;
			}
			else if(v.getId()==R.id.beendenbutton)
			{
				setContentView(R.layout.activity_main);
				start = (Button)findViewById(R.id.startbutton);
		        start.setOnClickListener(this);
		        begin = (TextView)findViewById(R.id.TextView1);
		        begin.setText("Um zu Beginnen drücke Start");
		        
		       
				return;
			}			
		}
	    
	   

	    public void setviewwischen(){
	    	
	    	setContentView(R.layout.wischen);
	    	cancel = (Button)findViewById(R.id.beendenbutton);
			cancel.setOnClickListener(this);
			state = (TextView)findViewById(R.id.textstate);
			state.setText("Zustand : STOPP");
	        LinearLayout  layoutScreen = (LinearLayout)findViewById(R.id.linearlayout);
	        layoutScreen.setOnTouchListener(this);

	    }
	    

	    public void onInit(int arg0){

	    	
	    	tts.setLanguage(Locale.GERMAN);
	   }
	    
	    
	    @Override
		public boolean onTouch(View v, MotionEvent event) {
	    	
	    	int vergleichy,vergleichx;
	    	int action = event.getAction();
	 
	    	
	    	if(action == MotionEvent.ACTION_DOWN)
	    	{
	    		//store the touch position
				x_touch = (int)event.getX();
				y_touch = (int)event.getY();

	    	}else if(action == MotionEvent.ACTION_UP) {
				int x = (int)event.getX();
				int y = (int)event.getY();
				
				vergleichx= x-x_touch;
				vergleichy=y-y_touch;
				
				
				if(vergleichx==0 && vergleichy==0)
				{
					state.setText("Stopp");
					tts.speak("Stopp", TextToSpeech.QUEUE_FLUSH, null);
				}else if(vergleichy < -10 && vergleichx >-20 && vergleichx <20)
				{
					state.setText("Vorwärts");
					tts.speak("Vorwärts", TextToSpeech.QUEUE_FLUSH, null);
				}else if(vergleichx > 10 && vergleichy > -20 && vergleichy <20)
					{
						state.setText("Rechts");
						tts.speak("Rechts", TextToSpeech.QUEUE_FLUSH, null);
					}else if(vergleichy > 10 && vergleichx < 20 && vergleichx >-20)
						{
						state.setText("Zurück");
						tts.speak("Zurück", TextToSpeech.QUEUE_FLUSH, null);
						}else if(vergleichx < -10 && vergleichy >-20 && vergleichy < 20)
							{
								state.setText("Links");
								tts.speak("Links", TextToSpeech.QUEUE_FLUSH, null);
							}
				
	    	}
	    	return true;
	    	}
	    

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

Und was mache ich mit der UI falsch, da du meinst das ich es aus einem UI Thread aus aufrufe?
 
AccepThread erbt von der Klasse Thread. Dort wird die run Methode überschrieben. Sinn und Zweck von Thread zu erben ist es die run Methode mit eigenem Code zu überschreiben und anschließend mithilfe von start den Thread zu starten, der dann anschließend die run Methode aufruft, die du überschrieben hast.

In Android ist es nicht erlaubt Netzwerk Operationen wie connect im Haupt/UI Thead zu starten. Da ich dort kein einziges "start" finde führst du alles in dem gleichen Thread aus. Das meldet dir eigentlich auch Android im Logcat. Das heißt du führst das "run" immer noch im selben Thread aus! Du rufst also einfach die run Methode deiner Klasse auf und erzeugst dafür keinen neuen Thread.

Code:
				AcceptThread connect = new AcceptThread(mbluetoothdevice.get(item));
				connect.run();
Alles im selben Thread.

Code:
				AcceptThread connect = new AcceptThread(mbluetoothdevice.get(item));
				connect.start();
Neue Thread für Netzwerkoperationen.

Du solltest definitiv die zweite Variante benutzen.

Vielleicht ist das auch schon die Lösung ;).
 
  • Danke
Reaktionen: Schütz12
Nun habe ich es geändert, jedoch weiß ich nicht ob ich mit dem Bluetooth-Gerät verbunden bin oder nicht. Wie kann ich dies überprüfen?
 
Öffne eine OutputStream und versuche Daten hinzuschicken oder versuch das was du eigentlich machen wolltest mit der Verbindung :D.
 
Leider muss ich feststellen das ich keine Verbindung mit dem Gerät bekomme :(

Was soll ich nun machen?

Hier ist der Code nocheinmal:

Code:
void dialog(){
    	
   	 //final CharSequence[] items = listItems.toArray(new CharSequence[listItems.size()]);
			CharSequence[] items = new CharSequence[mbluetoothdevice.size()];
	
	// collect names of BT devices for the list
			for (int i = 0; i < items.length; i++) {
				items[i] = mbluetoothdevice.get(i).getName();
				}

  
   	AlertDialog.Builder builder = new AlertDialog.Builder(this);
       builder.setTitle("devices");
       builder.setItems(items, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int item) {
               // Do something with the selection
        	 
        	   bluetoothAdapter.cancelDiscovery();
        	   AcceptThread connect = new AcceptThread(mbluetoothdevice.get(item));
        	   connect.start();
        	  
        	   
        	   
           }
       });
       AlertDialog alert = builder.create();
       alert.show();
   }
		
		
		private class AcceptThread extends Thread {	
			BluetoothSocket mmSocket;
			 BluetoothDevice mmDevice;
			 BluetoothSocket tmp;
			
			AcceptThread(BluetoothDevice device) {
				// Use a temporary object that is later assigned to mmSocket,
				// because mmSocket is final
				tmp = null;
				mmDevice = device;
	 
				// Get a BluetoothSocket to connect with the given BluetoothDevice
				try {
					// MY_UUID is the app's UUID string, also used by the server code
					tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
				} catch (IOException e) { }
				mmSocket = tmp;
	    }
	 
	    public void run() {
	        // Cancel discovery because it will slow down the connection
	 
	        try {
	            // Connect the device through the socket. This will block
	            // until it succeeds or throws an exception
	            mmSocket.connect();
	            
	        } catch (IOException connectException) {
	            // Unable to connect; close the socket and get out
	            try {
	                mmSocket.close();
	            } catch (IOException closeException) { }
	            return;
	        }
	        
	     }
	    
	    private BluetoothSocket getSocket(){
	    	return mmSocket;
	    }
	    
	  
		}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			  // TODO Auto-generated method stub
			  if(requestCode == REQUEST_ENABLE_BT){
			   CheckBlueToothState();
			  }
			 }

		
		BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){

			  @Override
			  public void onReceive(Context context, Intent intent) {
			   // TODO Auto-generated method stub
			   String action = intent.getAction();
			   if(BluetoothDevice.ACTION_FOUND.equals(action)) {
			             BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			             mbluetoothdevice.add(device);
			             dialog();
			   }
			  }};

Es muss noch an der .connect(); sein, sonst wüsste ich keinen Fehler.

Dies ist im LogCat gewesen als einziges wo BluetoothSocket dabei war.

01-10 18:27:39.074: D/BluetoothSocket(17448): connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[65]}


Könnte jemand mal den Code genau anschaun oder ihn sogar testen und ihn Richtig stellen

Danke!
 
Zurück
Oben Unten