Daten über Bluetooth senden+empfangen

  • Antworten:3
Daniel
  • Forum-Beiträge: 60

10.02.2013, 20:50:34 via Website

Hallo,

ich gerade dabei, meine erste App zu entwickeln, die Bluetooth verwendet. Ich bin auch schon recht weit gekommen. Bisher zeigt die App alle Bluetooth Geräte in Reichweite an und verbindet sich mit einem bestimmten. Im Moment verbindet sich die App automatisch mit einem im Voraus eingestellten Gerät, das ist nur zu Testzwecken so und wird später noch geändert. Außerdem gibt es noch ein EditTextfeld und einen Button, mit dem man den Text dieses Feldes an das verbundene Gerät senden können soll.
Mein Problem bei diesem Programm ist aber, dass sich die App immer aufhängt, nachdem sie eine Bluetoothverbindung zu einem Gerät hergestellt hat. Man kann dann als Benutzer einfach nichts mehr machen und nach kurzer Zeit stürzt es ohne Fehlermeldung komplett ab.
Ich hoffe ihr könnt mir helfen.

1public class StripeSetupActivity extends Activity implements OnClickListener {
2
3 public boolean btAktiviert = true;
4 ListView listDevicesFound;
5 TextView statusText;
6 Button sendButton;
7 EditText et;
8 ArrayAdapter<String> btArrayAdapter;
9 int anzahlGeraete;
10 ArrayList<BluetoothDevice> btGeraeteListe = new ArrayList<BluetoothDevice>();
11
12 @Override
13 public void onCreate(Bundle savedInstanceState) {
14 super.onCreate(savedInstanceState);
15 setContentView(R.layout.main);
16 listDevicesFound = (ListView)findViewById(R.id.listView1);
17 statusText = (TextView)findViewById(R.id.textView1);
18 sendButton = (Button) findViewById(R.id.button1);
19 et = (EditText) findViewById(R.id.editText1);
20 btArrayAdapter = new ArrayAdapter<String>(StripeSetupActivity.this, android.R.layout.simple_list_item_1);
21 System.out.println("gestartet");
22 sendButton.setOnClickListener(this);
23 setupBluetooth();
24 }
25
26 BluetoothAdapter mBluetoothAdapter;
27
28 public void setupBluetooth(){
29 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
30 if (mBluetoothAdapter == null) {
31 // Device does not support Bluetooth
32 }
33 if (!mBluetoothAdapter.isEnabled()) {
34 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
35 final int REQUEST_ENABLE_BT = 1;
36 startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
37 }
38 if(btAktiviert){
39 statusText.setText("Suche nach Bluetooth Geräten...");
40 anzahlGeraete = 0;
41 btGeraeteListe.clear();
42 Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); //bereits gepaarte Geräte anzeigen
43 if (pairedDevices.size() > 0) {
44 for (BluetoothDevice device : pairedDevices) {
45 String name = device.getName();
46 if(name == null || name == "null"){
47 name = "unbenannt";
48 }
49 btArrayAdapter.add(name + "\n" + device.getAddress());
50 anzahlGeraete++;
51 btGeraeteListe.add(device);
52 }
53 listDevicesFound.setAdapter(btArrayAdapter);
54 }
55
56 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); //neue Geräte suchen und anzeigen
57 filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
58 registerReceiver(mReceiver, filter);
59 mBluetoothAdapter.startDiscovery();
60 }
61 /**
62 **/
63 }
64
65
66 @Override
67 protected void onDestroy() {
68 this.unregisterReceiver(mReceiver);
69 super.onDestroy();
70 }
71
72 ConnectThread cont;
73
74
75 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
76 //@Override
77 public void onReceive(Context context, Intent intent) {
78 String action = intent.getAction();
79 // When discovery finds a device
80 if (BluetoothDevice.ACTION_FOUND.equals(action)) {
81 // Get the BluetoothDevice object from the Intent
82 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
83 if(!btGeraeteListe.contains(device)){
84 anzahlGeraete++;
85 btGeraeteListe.add(device);
86 btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
87 }
88 }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
89 {
90 statusText.setText(anzahlGeraete + " Bluetooth Geräte wurden gefunden.");
91 BluetoothDevice ledstripe = null;
92 for(int x = 0; x < btGeraeteListe.size(); x++){
93 if(btGeraeteListe.get(x).getAddress().equals("00:06:66:48:DE:C6")){
94 ledstripe = btGeraeteListe.get(x);
95 }
96 }
97 if(ledstripe != null){
98 System.out.println("ledstripe gefunden!");
99 cont = new ConnectThread(ledstripe);
100 cont.run();
101 }else{
102 System.out.println("ledstripe nicht gefunden!");
103 }
104 }
105 }
106 };
107
108 @Override
109 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
110 if (resultCode == RESULT_OK) {
111 System.out.println("Bluetooth aktiviert!");
112 btAktiviert = true;
113 }else{
114 System.out.println("Bluetooth nicht aktiviert!");
115 btAktiviert = false;
116 }
117 }
118
119 private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
120 ConnectedThread ct;
121
122 private class ConnectThread extends Thread {
123 private final BluetoothSocket mmSocket;
124 private final BluetoothDevice mmDevice;
125
126 public ConnectThread(BluetoothDevice device) {
127 // Use a temporary object that is later assigned to mmSocket,
128 // because mmSocket is final
129 BluetoothSocket tmp = null;
130 mmDevice = device;
131
132 // Get a BluetoothSocket to connect with the given BluetoothDevice
133 try {
134 // MY_UUID is the app's UUID string, also used by the server code
135 tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
136 } catch (IOException e) { }
137 mmSocket = tmp;
138 }
139
140 public void run() {
141 // Cancel discovery because it will slow down the connection
142 System.out.println("Verbunden!");
143 mBluetoothAdapter.cancelDiscovery();
144
145 try {
146 // Connect the device through the socket. This will block
147 // until it succeeds or throws an exception
148 mmSocket.connect();
149 } catch (IOException connectException) {
150 // Unable to connect; close the socket and get out
151 try {
152 mmSocket.close();
153 } catch (IOException closeException) { }
154 return;
155 }
156
157 // Do work to manage the connection (in a separate thread)
158 ct = new ConnectedThread(mmSocket);
159 ct.run();
160 }
161
162 /** Will cancel an in-progress connection, and close the socket */
163 public void cancel() {
164 try {
165 mmSocket.close();
166 } catch (IOException e) { }
167 }
168 }
169
170 final Handler handler = new Handler(){
171 @Override
172 public void handleMessage(Message msg){
173 System.out.println("Nachricht: " + msg.arg1);
174 statusText.setText(msg.arg1 + " - " + msg.arg2);
175 }
176 };
177
178 private class ConnectedThread extends Thread {
179 private final BluetoothSocket mmSocket;
180 private final InputStream mmInStream;
181 private final OutputStream mmOutStream;
182
183 public ConnectedThread(BluetoothSocket socket) {
184 System.out.println("Verbunden2!");
185 mmSocket = socket;
186 InputStream tmpIn = null;
187 OutputStream tmpOut = null;
188
189 // Get the input and output streams, using temp objects because
190 // member streams are final
191 try {
192 tmpIn = socket.getInputStream();
193 tmpOut = socket.getOutputStream();
194 } catch (IOException e) { }
195
196 mmInStream = tmpIn;
197 mmOutStream = tmpOut;
198 }
199
200 public void run() {
201 byte[] buffer = new byte[1024]; // buffer store for the stream
202 int bytes; // bytes returned from read()
203
204 // Keep listening to the InputStream until an exception occurs
205 while (true) {
206 try {
207 // Read from the InputStream
208 bytes = mmInStream.read(buffer);
209 // Send the obtained bytes to the UI activity
210 System.out.println("Nachricht empfangen!");
211 handler.obtainMessage(1, bytes, -1, buffer)
212 .sendToTarget();
213 } catch (IOException e) {
214 break;
215 }
216 }
217 }
218
219 /* Call this from the main activity to send data to the remote device */
220 public void write(byte[] bytes) {
221 try {
222 mmOutStream.write(bytes);
223 } catch (IOException e) { }
224 }
225
226 /* Call this from the main activity to shutdown the connection */
227 public void cancel() {
228 try {
229 mmSocket.close();
230 } catch (IOException e) { }
231 }
232 }
233
234 public byte[] intZuByte(int number){
235 byte[] data = new byte[4];
236
237 // int -> byte[]
238 for (int i = 0; i < 4; ++i) {
239 int shift = i << 3; // i * 8
240 data[3-i] = (byte)((number & (0xff << shift)) >>> shift);
241 }
242 return data;
243 }
244
245 @Override
246 public void onClick(View v) {
247 ct.write(intZuByte(Integer.valueOf(et.getText().toString())));
248 }
249}

— geändert am 11.02.2013, 19:42:29

Antworten
Markus B.
  • Forum-Beiträge: 636

11.02.2013, 08:13:40 via App

Hallo,
fang mal an die Exceptions zu loggen und zeig uns dann den StackTrace mit dem Fehler.

Gruß,
Markus

Antworten
Daniel
  • Forum-Beiträge: 60

11.02.2013, 19:13:04 via Website

Inzwischen habe ich den Fehler mit dem Abstürzen behoben. Der Fehler war, dass ich beim Aufrufen der Threads run() anstatt start() verwendet habe. Leider habe ich jetzt einen neuen Fehler. Ich kann jetzt zwar eine Verbindung zu einem Gerät herstellen ohne dass es abstürzt und auch Nachrichten senden, aber nichts empfangen. Ich habe den Code auch allgemein etwas überarbeitet.

neuer Code:
1public class StripeSetupActivity extends Activity implements OnClickListener {
2
3 public boolean btAktiviert = true;
4 ListView listDevicesFound;
5 TextView statusText;
6 Button sendButton;
7 EditText et;
8 ArrayAdapter<String> btArrayAdapter;
9 int anzahlGeraete;
10 ArrayList<BluetoothDevice> btGeraeteListe = new ArrayList<BluetoothDevice>();
11
12 @Override
13 public void onCreate(Bundle savedInstanceState) {
14 super.onCreate(savedInstanceState);
15 setContentView(R.layout.main);
16 listDevicesFound = (ListView)findViewById(R.id.listView1);
17 statusText = (TextView)findViewById(R.id.textView1);
18 sendButton = (Button) findViewById(R.id.button1);
19 et = (EditText) findViewById(R.id.editText1);
20 btArrayAdapter = new ArrayAdapter<String>(StripeSetupActivity.this, android.R.layout.simple_list_item_1);
21 System.out.println("gestartet");
22 sendButton.setOnClickListener(this);
23 }
24
25 @Override
26 protected void onStart() {
27 super.onStart();
28 setupBluetooth();
29 }
30
31 BluetoothAdapter mBluetoothAdapter;
32
33 public void setupBluetooth(){
34 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
35 if (mBluetoothAdapter == null) {
36 // Device does not support Bluetooth
37 }
38 if (!mBluetoothAdapter.isEnabled()) {
39 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
40 final int REQUEST_ENABLE_BT = 1;
41 startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
42 }
43 if(btAktiviert){
44 statusText.setText("Suche nach Bluetooth Geräten...");
45 anzahlGeraete = 0;
46 btGeraeteListe.clear();
47 btArrayAdapter.clear();
48 Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); //bereits gepaarte Geräte anzeigen
49 if (pairedDevices.size() > 0) {
50 for (BluetoothDevice device : pairedDevices) {
51 String name = device.getName();
52 if(name == null || name == "null"){
53 name = "unbenannt";
54 }
55 btArrayAdapter.add(name + "\n" + device.getAddress());
56 anzahlGeraete++;
57 btGeraeteListe.add(device);
58 }
59 listDevicesFound.setAdapter(btArrayAdapter);
60 }
61
62 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); //neue Geräte suchen und anzeigen
63 filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
64 registerReceiver(mReceiver, filter);
65 mBluetoothAdapter.startDiscovery();
66 }
67 }
68
69 @Override
70 protected void onDestroy() {
71 this.unregisterReceiver(mReceiver);
72 super.onDestroy();
73 }
74
75 ConnectThread cont;
76 BluetoothSocket mmSocket = null;
77
78 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
79
80 @Override
81 public void onReceive(Context context, Intent intent) {
82 String action = intent.getAction();
83 if (BluetoothDevice.ACTION_FOUND.equals(action)) { //Gerät gefunden
84 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
85 if(!btGeraeteListe.contains(device)){
86 anzahlGeraete++;
87 btGeraeteListe.add(device);
88 btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
89 }
90 }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){ //Suche abgeschlossen
91 statusText.setText(anzahlGeraete + " Bluetooth Geräte wurden gefunden.");
92 BluetoothDevice ledstripe = null;
93 for(int x = 0; x < btGeraeteListe.size(); x++){
94 if(btGeraeteListe.get(x).getAddress().equals("00:06:66:48:DE:C6")){
95 ledstripe = btGeraeteListe.get(x);
96 }
97 }
98 if(ledstripe != null){
99 System.out.println("ledstripe gefunden!");
100 cont = new ConnectThread(ledstripe);
101 cont.start();
102 }else{
103 System.out.println("ledstripe nicht gefunden!");
104 }
105 }
106 }
107 };
108
109 @Override
110 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
111 if (resultCode == RESULT_OK) {
112 System.out.println("Bluetooth aktiviert!");
113 btAktiviert = true;
114 }else{
115 System.out.println("Bluetooth nicht aktiviert!");
116 btAktiviert = false;
117 }
118 }
119
120 private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
121 BluetoothDevice mmDevice;
122 InputStream mmInStream;
123 OutputStream mmOutStream;
124
125 private class ConnectThread extends Thread {
126
127 public ConnectThread(BluetoothDevice device) {
128 BluetoothSocket tmp = null;
129 mBluetoothAdapter.cancelDiscovery();
130 mmDevice = device;
131
132 try {
133 tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
134 } catch (IOException e) {
135 System.out.println("Fehler1: "+e);
136 }
137 mmSocket = tmp;
138 }
139
140 public void run() {
141 System.out.println("Verbunden!");
142
143 try {
144 mmSocket.connect();
145 } catch (IOException connectException) {
146 System.out.println("Fehler2: "+ connectException);// Unable to connect; close the socket and get out
147 try {
148 mmSocket.close();
149 } catch (IOException closeException) {
150 System.out.println("Fehler3: "+ closeException);
151 }
152 return;
153 }
154
155 InputStream tmpIn = null;
156 OutputStream tmpOut = null;
157 try {
158 tmpIn = mmSocket.getInputStream();
159 tmpOut = mmSocket.getOutputStream();
160 } catch (IOException e) {
161 System.out.println("Fehler5: "+e);
162 }
163
164 mmInStream = tmpIn;
165 mmOutStream = tmpOut;
166
167 byte[] buffer = new byte[1024]; // buffer store for the stream
168 int bytes; // bytes returned from read()
169 System.out.println("ConnectedThread");
170
171 while (true) { //Nachrichten empfangen
172 try {
173 bytes = mmInStream.read(buffer);
174 System.out.println("Nachricht empfangen!");
175 handler.obtainMessage(1, bytes, -1, buffer)
176 .sendToTarget();
177 } catch (IOException e) {
178 System.out.println("Fehler6: "+e);
179 break;
180 }
181 }
182 }
183
184 public void cancel() {
185 try {
186 mmSocket.close();
187 } catch (IOException e) {
188 System.out.println("Fehler4: "+ e);
189 }
190 }
191 }
192
193 public void write(byte[] bytes) { //Nachrich an Bluetooth Gerät senden
194 try {
195 mmOutStream.write(bytes);
196 } catch (IOException e) {
197 System.out.println("Fehler8: "+ e);
198 }
199 }
200
201 final Handler handler = new Handler(){
202 @Override
203 public void handleMessage(Message msg){ //Nachricht von Bluetooth Gerät wurde empfangen
204 System.out.println("Nachricht: " + msg.arg1);
205 statusText.setText(msg.arg1 + " - " + msg.arg2);
206 }
207 };
208
209 public byte[] intZuByte(int number){
210 byte[] data = new byte[4];
211
212 for (int i = 0; i < 4; ++i) {
213 int shift = i << 3; // i * 8
214 data[3-i] = (byte)((number & (0xff << shift)) >>> shift);
215 }
216 return data;
217 }
218
219 @Override
220 public void onClick(View v) { //Button zum Senden wurde gedrückt
221 write(intZuByte(Integer.valueOf(et.getText().toString())));
222 }
223}

Logcat:
02-11 18:36:24.680: I/System.out(16080): gestartet
02-11 18:36:24.795: D/CLIPBOARD(16080): Hide Clipboard dialog at Starting input: finished by someone else... !
02-11 18:36:35.010: I/System.out(16080): ledstripe gefunden!
02-11 18:36:35.040: V/BluetoothSocket.cpp(16080): initSocketNative
02-11 18:36:35.040: V/BluetoothSocket.cpp(16080): ...fd 64 created (RFCOMM, lm = 26)
02-11 18:36:35.040: V/BluetoothSocket.cpp(16080): initSocketFromFdNative
02-11 18:36:35.070: I/System.out(16080): Verbunden!
02-11 18:36:35.085: D/BluetoothUtils(16080): isSocketAllowedBySecurityPolicy start : device null
02-11 18:36:35.955: V/BluetoothSocket.cpp(16080): connectNative
02-11 18:36:36.390: V/BluetoothSocket.cpp(16080): ...connect(64, RFCOMM) = 0 (errno 115)
02-11 18:36:36.390: I/System.out(16080): ConnectedThread
02-11 18:36:36.390: V/BluetoothSocket.cpp(16080): readNative
02-11 18:36:42.040: V/BluetoothSocket.cpp(16080): writeNative <- Diese Einträge entstehen beim Klicken auf den Button
02-11 18:36:42.930: V/BluetoothSocket.cpp(16080): writeNative
02-11 18:36:43.455: V/BluetoothSocket.cpp(16080): writeNative
02-11 18:36:43.805: V/BluetoothSocket.cpp(16080): writeNative

— geändert am 11.02.2013, 19:13:52

Antworten
Gelöschter Account
  • Forum-Beiträge: 8.246

11.02.2013, 19:18:53 via Website

Hallo

Bitte bearbeite noch mal deinen Threadtitel gemäß unserer Regeln, damit auch klar wird worum es überhaupt geht.
Um den Threadtitel zu ändern musst du im ersten Posting auf "Bearbeiten" klicken.
Danke.

Freakyno1
Das AndroidPIT Moderatoren und Administratoren Team

Antworten