Bluetooth daten live anzeigen

Diese Seite verwendet Cookies. Durch die Nutzung unserer Seite erklären Sie sich damit einverstanden, dass wir Cookies setzen. Weitere Informationen

  • Bluetooth daten live anzeigen

    Hallo,

    mein Ziel ist es Messwerte die per Bluetooth von einem Microcontroller kommen zu empfangen und live anzuzeigen.
    Bisher habe ich nur den untenstehendne quellcode. Wie muss ich als nächste vorgehen. Bin leider anfänger und verstehe 2 den untenstehenden code( ist aus einem Beispiel) weiß aber nicht wie ich weiter vorgehen soll.

    DAnke für eure Hilfe





    Java-Quellcode

    1. package com.test.bluetooth;
    2. import java.io.IOException;
    3. import java.io.InputStream;
    4. import java.io.OutputStream;
    5. import java.util.ArrayList;
    6. import java.util.Set;
    7. import java.util.UUID;
    8. import android.app.Activity;
    9. import android.bluetooth.BluetoothAdapter;
    10. import android.bluetooth.BluetoothDevice;
    11. import android.bluetooth.BluetoothSocket;
    12. import android.content.BroadcastReceiver;
    13. import android.content.Context;
    14. import android.content.Intent;
    15. import android.content.IntentFilter;
    16. import android.os.Bundle;
    17. import android.os.Handler;
    18. import android.os.Message;
    19. import android.util.Log;
    20. import android.view.View;
    21. import android.widget.AdapterView;
    22. import android.widget.AdapterView.OnItemClickListener;
    23. import android.widget.ArrayAdapter;
    24. import android.widget.ListView;
    25. import android.widget.Toast;
    26. public class Main_Activity extends Activity implements OnItemClickListener {
    27. ArrayAdapter<String> listAdapter;
    28. ListView listView;
    29. BluetoothAdapter btAdapter;
    30. Set<BluetoothDevice> devicesArray;
    31. ArrayList<String> pairedDevices;
    32. ArrayList<BluetoothDevice> devices;
    33. public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    34. protected static final int SUCCESS_CONNECT = 0;
    35. protected static final int MESSAGE_READ = 1;
    36. IntentFilter filter;
    37. BroadcastReceiver receiver;
    38. String tag = "debugging";
    39. Handler mHandler = new Handler(){
    40. @Override
    41. public void handleMessage(Message msg) {
    42. // TODO Auto-generated method stub
    43. Log.i(tag, "in handler");
    44. super.handleMessage(msg);
    45. switch(msg.what){
    46. case SUCCESS_CONNECT:
    47. // DO something
    48. ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
    49. Toast.makeText(getApplicationContext(), "CONNECT", 0).show();
    50. String s = "successfully connected";
    51. connectedThread.write(s.getBytes());
    52. Log.i(tag, "connected");
    53. break;
    54. case MESSAGE_READ:
    55. byte[] readBuf = (byte[])msg.obj;
    56. String string = new String(readBuf);
    57. Toast.makeText(getApplicationContext(), string, 0).show();
    58. break;
    59. }
    60. }
    61. };
    62. @Override
    63. public void onCreate(Bundle savedInstanceState) {
    64. super.onCreate(savedInstanceState);
    65. setContentView(R.layout.main);
    66. init();
    67. if(btAdapter==null){
    68. Toast.makeText(getApplicationContext(), "No bluetooth detected", 0).show();
    69. finish();
    70. }
    71. else{
    72. if(!btAdapter.isEnabled()){
    73. turnOnBT();
    74. }
    75. getPairedDevices();
    76. startDiscovery();
    77. }
    78. }
    79. private void startDiscovery() {
    80. // TODO Auto-generated method stub
    81. btAdapter.cancelDiscovery();
    82. btAdapter.startDiscovery();
    83. }
    84. private void turnOnBT() {
    85. // TODO Auto-generated method stub
    86. Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    87. startActivityForResult(intent, 1);
    88. }
    89. private void getPairedDevices() {
    90. // TODO Auto-generated method stub
    91. devicesArray = btAdapter.getBondedDevices();
    92. if(devicesArray.size()>0){
    93. for(BluetoothDevice device:devicesArray){
    94. pairedDevices.add(device.getName());
    95. }
    96. }
    97. }
    98. private void init() {
    99. // TODO Auto-generated method stub
    100. listView=(ListView)findViewById(R.id.listView);
    101. listView.setOnItemClickListener(this);
    102. listAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
    103. listView.setAdapter(listAdapter);
    104. btAdapter = BluetoothAdapter.getDefaultAdapter();
    105. pairedDevices = new ArrayList<String>();
    106. filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    107. devices = new ArrayList<BluetoothDevice>();
    108. receiver = new BroadcastReceiver(){
    109. @Override
    110. public void onReceive(Context context, Intent intent) {
    111. // TODO Auto-generated method stub
    112. String action = intent.getAction();
    113. if(BluetoothDevice.ACTION_FOUND.equals(action)){
    114. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    115. devices.add(device);
    116. String s = "";
    117. for(int a = 0; a < pairedDevices.size(); a++){
    118. if(device.getName().equals(pairedDevices.get(a))){
    119. //append
    120. s = "(Paired)";
    121. break;
    122. }
    123. }
    124. listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
    125. }
    126. else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
    127. // run some code
    128. }
    129. else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
    130. // run some code
    131. }
    132. else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
    133. if(btAdapter.getState() == btAdapter.STATE_OFF){
    134. turnOnBT();
    135. }
    136. }
    137. }
    138. };
    139. registerReceiver(receiver, filter);
    140. filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    141. registerReceiver(receiver, filter);
    142. filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    143. registerReceiver(receiver, filter);
    144. filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    145. registerReceiver(receiver, filter);
    146. }
    147. @Override
    148. protected void onPause() {
    149. // TODO Auto-generated method stub
    150. super.onPause();
    151. unregisterReceiver(receiver);
    152. }
    153. @Override
    154. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    155. // TODO Auto-generated method stub
    156. super.onActivityResult(requestCode, resultCode, data);
    157. if(resultCode == RESULT_CANCELED){
    158. Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
    159. finish();
    160. }
    161. }
    162. public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
    163. long arg3) {
    164. // TODO Auto-generated method stub
    165. if(btAdapter.isDiscovering()){
    166. btAdapter.cancelDiscovery();
    167. }
    168. if(listAdapter.getItem(arg2).contains("Paired")){
    169. BluetoothDevice selectedDevice = devices.get(arg2);
    170. ConnectThread connect = new ConnectThread(selectedDevice);
    171. connect.start();
    172. Log.i(tag, "in click listener");
    173. }
    174. else{
    175. Toast.makeText(getApplicationContext(), "device is not paired", 0).show();
    176. }
    177. }
    178. private class ConnectThread extends Thread {
    179. private final BluetoothSocket mmSocket;
    180. private final BluetoothDevice mmDevice;
    181. public ConnectThread(BluetoothDevice device) {
    182. // Use a temporary object that is later assigned to mmSocket,
    183. // because mmSocket is final
    184. BluetoothSocket tmp = null;
    185. mmDevice = device;
    186. Log.i(tag, "construct");
    187. // Get a BluetoothSocket to connect with the given BluetoothDevice
    188. try {
    189. // MY_UUID is the app's UUID string, also used by the server code
    190. tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
    191. } catch (IOException e) {
    192. Log.i(tag, "get socket failed");
    193. }
    194. mmSocket = tmp;
    195. }
    196. public void run() {
    197. // Cancel discovery because it will slow down the connection
    198. btAdapter.cancelDiscovery();
    199. Log.i(tag, "connect - run");
    200. try {
    201. // Connect the device through the socket. This will block
    202. // until it succeeds or throws an exception
    203. mmSocket.connect();
    204. Log.i(tag, "connect - succeeded");
    205. } catch (IOException connectException) { Log.i(tag, "connect failed");
    206. // Unable to connect; close the socket and get out
    207. try {
    208. mmSocket.close();
    209. } catch (IOException closeException) { }
    210. return;
    211. }
    212. // Do work to manage the connection (in a separate thread)
    213. mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
    214. }
    215. /** Will cancel an in-progress connection, and close the socket */
    216. public void cancel() {
    217. try {
    218. mmSocket.close();
    219. } catch (IOException e) { }
    220. }
    221. }
    222. private class ConnectedThread extends Thread {
    223. private final BluetoothSocket mmSocket;
    224. private final InputStream mmInStream;
    225. private final OutputStream mmOutStream;
    226. public ConnectedThread(BluetoothSocket socket) {
    227. mmSocket = socket;
    228. InputStream tmpIn = null;
    229. OutputStream tmpOut = null;
    230. // Get the input and output streams, using temp objects because
    231. // member streams are final
    232. try {
    233. tmpIn = socket.getInputStream();
    234. tmpOut = socket.getOutputStream();
    235. } catch (IOException e) { }
    236. mmInStream = tmpIn;
    237. mmOutStream = tmpOut;
    238. }
    239. public void run() {
    240. byte[] buffer; // buffer store for the stream
    241. int bytes; // bytes returned from read()
    242. // Keep listening to the InputStream until an exception occurs
    243. while (true) {
    244. try {
    245. // Read from the InputStream
    246. buffer = new byte[1024];
    247. bytes = mmInStream.read(buffer);
    248. // Send the obtained bytes to the UI activity
    249. mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
    250. .sendToTarget();
    251. } catch (IOException e) {
    252. break;
    253. }
    254. }
    255. }
    256. /* Call this from the main activity to send data to the remote device */
    257. public void write(byte[] bytes) {
    258. try {
    259. mmOutStream.write(bytes);
    260. } catch (IOException e) { }
    261. }
    262. /* Call this from the main activity to shutdown the connection */
    263. public void cancel() {
    264. try {
    265. mmSocket.close();
    266. } catch (IOException e) { }
    267. }
    268. }
    269. }
    Alles anzeigen

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von gammel ()

  • Magst Du bitte den Quellcode einmal im 'Quellcode' Modus des Beitragseditors zischen die code - Tags einfügen?
    Sonst gehen die Zeilenumbrüche kaputt, und das ist wirklich ätzend. Vor allem bei so langen Codes.
    Je mehr Käse, desto mehr Löcher.
    Je mehr Löcher, desto weniger Käse.
    Daraus folgt: je mehr Käse, desto weniger Käse.

    »Dies ist ein Forum. Schreibt Eure Fragen in das Forum, nicht per PN!«
  • Hier musst Du Dich wohl ein wenig in die Handler einlesen.

    Stichwort: Im case MESSAGE_READ: alles einbauen, was Du zur Darstellung benötigst.
    Je mehr Käse, desto mehr Löcher.
    Je mehr Löcher, desto weniger Käse.
    Daraus folgt: je mehr Käse, desto weniger Käse.

    »Dies ist ein Forum. Schreibt Eure Fragen in das Forum, nicht per PN!«
  • Danke für deine Antworten, aber ich finde keinen Anfangspunkt wo ich anfangen kann und wie es grob ausseen sollte.


    hab nur mal ein paar Zeilen "Ideensammlung" :

    Java-Quellcode

    1. private Handler handler = new Handler() {
    2. handler.handleMessage();
    3. bytes = mmInStream.read(buffer);
    4. m.Handler.obtainMessage(Message_Read, bytes, -1, buffer).sendToTarget();
    5. value = bytes;
    6. handler.post(new "Klassenname"(){
    7. public void run();{
    8. TextView.set TextView(value);
    9. }
    10. }
    Alles anzeigen



    könnte mir irgendjemand weiterhelfen?
  • Du sollst Dich an den Zweig ranhängen:

    Quellcode

    1. case MESSAGE_READ:
    2. byte[] readBuf = (byte[])msg.obj;
    3. String string = new String(readBuf);
    4. Toast.makeText(getApplicationContext(), string, 0).show();
    5. break;


    Der müsste Dir ja permanent via Toast mitteilen, dass Du Daten gesendet bekommen hast.
    Je mehr Käse, desto mehr Löcher.
    Je mehr Löcher, desto weniger Käse.
    Daraus folgt: je mehr Käse, desto weniger Käse.

    »Dies ist ein Forum. Schreibt Eure Fragen in das Forum, nicht per PN!«