Daniel
- Forum-Beiträge: 60
10.02.2013, 20:50:34 via Website
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.
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:48E: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}
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:48E: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
Empfohlener redaktioneller Inhalt
Mit Deiner Zustimmung wird hier ein externer Inhalt geladen.
Mit Klick auf den oben stehenden Button erklärst Du Dich damit einverstanden, dass Dir externe Inhalte angezeigt werden dürfen. Dabei können personenbezogene Daten an Drittanbieter übermittelt werden. Mehr Infos dazu findest Du in unserer Datenschutzerklärung.