Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.67 KB | None | 0 0
  1. MainActivity.xml
  2.  
  3. package c.java.essora;
  4.  
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.util.UUID;
  9. import android.app.Activity;
  10. import android.bluetooth.BluetoothAdapter;
  11. import android.bluetooth.BluetoothDevice;
  12. import android.bluetooth.BluetoothSocket;
  13. import android.content.Intent;
  14. import android.os.Bundle;
  15. import android.os.Handler;
  16. import android.util.Log;
  17. import android.view.View;
  18. import android.view.View.OnClickListener;
  19. import android.widget.Button;
  20. import android.widget.SeekBar;
  21. import android.widget.TextView;
  22. import android.widget.Toast;
  23.  
  24. public class MainActivity extends Activity {
  25.  
  26. Button btnOn, btnOff;
  27. TextView txtArduino, txtString, txtStringLength, sensorView0, sensorView1, sensorView2, sensorView3;
  28. TextView txtSendorLDR;
  29. Handler bluetoothIn;
  30.  
  31. final int handlerState = 0; //used to identify handler message
  32. private BluetoothAdapter btAdapter = null;
  33. private BluetoothSocket btSocket = null;
  34. private StringBuilder recDataString = new StringBuilder();
  35.  
  36. private ConnectedThread mConnectedThread;
  37.  
  38. // SPP UUID service - this should work for most devices
  39. private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  40.  
  41. // String for MAC address
  42. private static String address = null;
  43.  
  44. @Override
  45. public void onCreate(Bundle savedInstanceState) {
  46. super.onCreate(savedInstanceState);
  47.  
  48. setContentView(R.layout.activity_main);
  49.  
  50. //Link the buttons and textViews to respective views
  51. btnOn = (Button) findViewById(R.id.buttonOn);
  52. btnOff = (Button) findViewById(R.id.buttonOff);
  53. txtString = (TextView) findViewById(R.id.txtString);
  54. txtStringLength = (TextView) findViewById(R.id.testView1);
  55. sensorView0 = (TextView) findViewById(R.id.sensorView0);
  56. sensorView1 = (TextView) findViewById(R.id.sensorView1);
  57. sensorView2 = (TextView) findViewById(R.id.sensorView2);
  58. sensorView3 = (TextView) findViewById(R.id.sensorView3);
  59.  
  60. txtSendorLDR = (TextView) findViewById(R.id.tv_sendorldr);
  61.  
  62.  
  63. bluetoothIn = new Handler() {
  64. public void handleMessage(android.os.Message msg) {
  65. if (msg.what == handlerState) { //if message is what we want
  66. String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
  67. recDataString.append(readMessage); //keep appending to string until ~
  68. int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
  69. if (endOfLineIndex > 0) { // make sure there data before ~
  70. String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
  71. txtString.setText("Datos recibidos = " + dataInPrint);
  72. int dataLength = dataInPrint.length(); //get length of data received
  73. txtStringLength.setText("Tamaño del String = " + String.valueOf(dataLength));
  74.  
  75. if (recDataString.charAt(0) == '#') //if it starts with # we know it is what we are looking for
  76. {
  77. String sensor0 = recDataString.substring(1, 5); //get sensor value from string between indices 1-5
  78. String sensor1 = recDataString.substring(6, 10); //same again...
  79. String sensor2 = recDataString.substring(11, 15);
  80. String sensor3 = recDataString.substring(16, 20);
  81.  
  82. if(sensor0.equals("1.00"))
  83. sensorView0.setText("Encendido"); //update the textviews with sensor values
  84. else
  85. sensorView0.setText("Apagado"); //update the textviews with sensor values
  86. sensorView1.setText(sensor1);
  87. sensorView2.setText(sensor2);
  88. sensorView3.setText(sensor3);
  89. //sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
  90. }
  91. recDataString.delete(0, recDataString.length()); //clear all string data
  92. // strIncom =" ";
  93. dataInPrint = " ";
  94. }
  95. }
  96. }
  97. };
  98.  
  99. btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
  100. checkBTState();
  101.  
  102.  
  103. // Set up onClick listeners for buttons to send 1 or 0 to turn on/off LED
  104. btnOff.setOnClickListener(new OnClickListener() {
  105. public void onClick(View v) {
  106. mConnectedThread.write("2"); // Send "0" via Bluetooth
  107. Toast.makeText(getBaseContext(), "Apagar el LED", Toast.LENGTH_SHORT).show();
  108. }
  109. });
  110.  
  111. btnOn.setOnClickListener(new OnClickListener() {
  112. public void onClick(View v) {
  113. mConnectedThread.write("1"); // Send "1" via Bluetooth
  114. Toast.makeText(getBaseContext(), "Encender el LED", Toast.LENGTH_SHORT).show();
  115. }
  116. });
  117. }
  118.  
  119.  
  120. private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
  121.  
  122. return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
  123. //creates secure outgoing connecetion with BT device using UUID
  124. }
  125.  
  126. @Override
  127. public void onResume() {
  128. super.onResume();
  129.  
  130. //Get MAC address from DeviceListActivity via intent
  131. Intent intent = getIntent();
  132.  
  133. //Get the MAC address from the DeviceListActivty via EXTRA
  134. address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
  135.  
  136. //create device and set the MAC address
  137. //Log.i("ramiro", "adress : " + address);
  138. BluetoothDevice device = btAdapter.getRemoteDevice(address);
  139.  
  140. try {
  141. btSocket = createBluetoothSocket(device);
  142. } catch (IOException e) {
  143. Toast.makeText(getBaseContext(), "La creacción del Socket fallo", Toast.LENGTH_LONG).show();
  144. }
  145. // Establish the Bluetooth socket connection.
  146. try
  147. {
  148. btSocket.connect();
  149. } catch (IOException e) {
  150. try
  151. {
  152. btSocket.close();
  153. } catch (IOException e2)
  154. {
  155. //insert code to deal with this
  156. }
  157. }
  158. mConnectedThread = new ConnectedThread(btSocket);
  159. mConnectedThread.start();
  160.  
  161. //I send a character when resuming.beginning transmission to check device is connected
  162. //If it is not an exception will be thrown in the write method and finish() will be called
  163. mConnectedThread.write("x");
  164. }
  165.  
  166. @Override
  167. public void onPause()
  168. {
  169. super.onPause();
  170. try
  171. {
  172. //Don't leave Bluetooth sockets open when leaving activity
  173. btSocket.close();
  174. } catch (IOException e2) {
  175. //insert code to deal with this
  176. }
  177. }
  178.  
  179. //Checks that the Android device Bluetooth is available and prompts to be turned on if off
  180. private void checkBTState() {
  181.  
  182. if(btAdapter==null) {
  183. Toast.makeText(getBaseContext(), "El dispositivo no soporta bluetooth", Toast.LENGTH_LONG).show();
  184. } else {
  185. if (btAdapter.isEnabled()) {
  186. } else {
  187. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  188. startActivityForResult(enableBtIntent, 1);
  189. }
  190. }
  191. }
  192.  
  193. //create new class for connect thread
  194. private class ConnectedThread extends Thread {
  195. private final InputStream mmInStream;
  196. private final OutputStream mmOutStream;
  197.  
  198. //creation of the connect thread
  199. public ConnectedThread(BluetoothSocket socket) {
  200. InputStream tmpIn = null;
  201. OutputStream tmpOut = null;
  202.  
  203. try {
  204. //Create I/O streams for connection
  205. tmpIn = socket.getInputStream();
  206. tmpOut = socket.getOutputStream();
  207. } catch (IOException e) { }
  208.  
  209. mmInStream = tmpIn;
  210. mmOutStream = tmpOut;
  211. }
  212.  
  213.  
  214. public void run() {
  215. byte[] buffer = new byte[256];
  216. int bytes;
  217.  
  218. // Keep looping to listen for received messages
  219. while (true) {
  220. try {
  221. bytes = mmInStream.read(buffer); //read bytes from input buffer
  222. String readMessage = new String(buffer, 0, bytes);
  223. // Send the obtained bytes to the UI Activity via handler
  224. bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
  225. } catch (IOException e) {
  226. break;
  227. }
  228. }
  229. }
  230. //write method
  231. public void write(String input) {
  232. byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
  233. try {
  234. mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
  235. } catch (IOException e) {
  236. //if you cannot write, close the application
  237. Toast.makeText(getBaseContext(), "La Conexión fallo", Toast.LENGTH_LONG).show();
  238. finish();
  239.  
  240. }
  241. }
  242. }
  243. }
  244.  
  245.  
  246.  
  247.  
  248.  
  249. ******* DeviceListActivity.xml**********
  250. package c.java.essora;
  251.  
  252. import java.util.Set;
  253. import android.app.Activity;
  254. import android.bluetooth.BluetoothAdapter;
  255. import android.bluetooth.BluetoothDevice;
  256. import android.content.Intent;
  257. import android.os.Bundle;
  258. import android.util.Log;
  259. import android.view.View;
  260. import android.widget.AdapterView;
  261. import android.widget.ArrayAdapter;
  262. import android.widget.Button;
  263. import android.widget.ListView;
  264. import android.widget.TextView;
  265. import android.widget.Toast;
  266. import android.widget.AdapterView.OnItemClickListener;
  267.  
  268.  
  269. public class DeviceListActivity extends Activity {
  270. // Debugging for LOGCAT
  271. private static final String TAG = "DeviceListActivity";
  272. private static final boolean D = true;
  273.  
  274.  
  275. // declare button for launching website and textview for connection status
  276. Button tlbutton;
  277. TextView textView1;
  278.  
  279. // EXTRA string to send on to mainactivity
  280. public static String EXTRA_DEVICE_ADDRESS = "device_address";
  281.  
  282. // Member fields
  283. private BluetoothAdapter mBtAdapter;
  284. private ArrayAdapter<String> mPairedDevicesArrayAdapter;
  285.  
  286. @Override
  287. protected void onCreate(Bundle savedInstanceState) {
  288. super.onCreate(savedInstanceState);
  289. setContentView(R.layout.device_list);
  290. }
  291.  
  292. @Override
  293. public void onResume()
  294. {
  295. super.onResume();
  296. //***************
  297. checkBTState();
  298.  
  299. textView1 = (TextView) findViewById(R.id.connecting);
  300. textView1.setTextSize(40);
  301. textView1.setText(" ");
  302.  
  303. // Initialize array adapter for paired devices
  304. mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
  305.  
  306. // Find and set up the ListView for paired devices
  307. ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
  308. pairedListView.setAdapter(mPairedDevicesArrayAdapter);
  309. pairedListView.setOnItemClickListener(mDeviceClickListener);
  310.  
  311. // Get the local Bluetooth adapter
  312. mBtAdapter = BluetoothAdapter.getDefaultAdapter();
  313.  
  314. // Get a set of currently paired devices and append to 'pairedDevices'
  315. Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
  316.  
  317. // Add previosuly paired devices to the array
  318. if (pairedDevices.size() > 0) {
  319. findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);//make title viewable
  320. for (BluetoothDevice device : pairedDevices) {
  321. mPairedDevicesArrayAdapter.add(device.getName() + "n" + device.getAddress());
  322. }
  323. } else {
  324. String noDevices = getResources().getText(R.string.app_name).toString();
  325. mPairedDevicesArrayAdapter.add(noDevices);
  326. }
  327. }
  328.  
  329. // Set up on-click listener for the list (nicked this - unsure)
  330. private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
  331. public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
  332.  
  333. textView1.setText("Conectando...");
  334. // Get the device MAC address, which is the last 17 chars in the View
  335. String info = ((TextView) v).getText().toString();
  336. String address = info.substring(info.length() - 17);
  337.  
  338. // Make an intent to start next activity while taking an extra which is the MAC address.
  339. Intent i = new Intent(DeviceListActivity.this, MainActivity.class);
  340. i.putExtra(EXTRA_DEVICE_ADDRESS, address);
  341. startActivity(i);
  342. }
  343. };
  344.  
  345. private void checkBTState() {
  346. // Check device has Bluetooth and that it is turned on
  347. mBtAdapter=BluetoothAdapter.getDefaultAdapter(); // CHECK THIS OUT THAT IT WORKS!!!
  348. if(mBtAdapter==null) {
  349. Toast.makeText(getBaseContext(), "El dispositivo no soporta Bluetooth", Toast.LENGTH_SHORT).show();
  350. } else {
  351. if (mBtAdapter.isEnabled()) {
  352. Log.d(TAG, "...Bluetooth Activado...");
  353. } else {
  354. //Prompt user to turn on Bluetooth
  355. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  356. startActivityForResult(enableBtIntent, 1);
  357.  
  358. }
  359. }
  360. }
  361. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement