Advertisement
Guest User

Untitled

a guest
Feb 27th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.94 KB | None | 0 0
  1. package com.csp.carservices;
  2.  
  3. import android.app.Activity;
  4. import android.bluetooth.BluetoothAdapter;
  5. import android.bluetooth.BluetoothDevice;
  6. import android.bluetooth.BluetoothServerSocket;
  7. import android.bluetooth.BluetoothSocket;
  8. import android.content.BroadcastReceiver;
  9. import android.content.Context;
  10. import android.content.Intent;
  11. import android.content.IntentFilter;
  12. import android.support.v7.app.AppCompatActivity;
  13. import android.os.Bundle;
  14. import android.view.Menu;
  15. import android.view.MenuItem;
  16. import android.view.View;
  17. import android.widget.AdapterView;
  18. import android.widget.ArrayAdapter;
  19. import android.widget.Button;
  20. import android.widget.ListView;
  21. import android.widget.Toast;
  22. import android.widget.ToggleButton;
  23.  
  24. import java.io.IOException;
  25. import java.util.Set;
  26. import java.util.UUID;
  27.  
  28. public class Bluetooth extends AppCompatActivity {
  29.  
  30.  
  31. private final static UUID uuid = UUID.fromString("59b4fb6c-5c46-4867-93fc-f46e072f3b87");
  32.  
  33. // Create a BroadcastReceiver for ACTION_FOUND
  34. private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
  35. public void onReceive(Context context, Intent intent) {
  36. String action = intent.getAction();
  37. // Whenever a remote Bluetooth device is found
  38. if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  39. // Get the BluetoothDevice object from the Intent
  40. BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  41. // Add the name and address to an array adapter to show in a ListView
  42. adapter.add(bluetoothDevice.getName() + "n"
  43. + bluetoothDevice.getAddress());
  44. }
  45. }
  46. };
  47.  
  48. private BluetoothAdapter bluetoothAdapter;
  49. private ToggleButton toggleButton;
  50. private Button dis;
  51. private ListView listview;
  52. private ArrayAdapter adapter;
  53. private static final int ENABLE_BT_REQUEST_CODE = 1;
  54. private static final int DISCOVERABLE_BT_REQUEST_CODE = 2;
  55. private static final int DISCOVERABLE_DURATION = 300;
  56.  
  57.  
  58. @Override
  59. protected void onCreate(Bundle savedInstanceState) {
  60. super.onCreate(savedInstanceState);
  61. setContentView(R.layout.activity_bluetooth);
  62.  
  63.  
  64. toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
  65.  
  66. listview = (ListView) findViewById(R.id.listView);
  67.  
  68. adapter = new ArrayAdapter
  69. (this,android.R.layout.simple_list_item_1);
  70. listview.setAdapter(adapter);
  71. bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  72.  
  73.  
  74. listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  75. @Override
  76. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  77. String itemValue = (String) listview.getItemAtPosition(position);
  78. String MAC = itemValue.substring(itemValue.length() - 17);
  79. BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(MAC);
  80. // Initiate a connection request in a separate thread
  81. ConnectingThread t = new ConnectingThread(bluetoothDevice);
  82. t.start();
  83.  
  84. }
  85. });
  86.  
  87. }
  88.  
  89.  
  90.  
  91.  
  92. public void onToggleClicked(View view) {
  93.  
  94. adapter.clear();
  95.  
  96. ToggleButton toggleButton = (ToggleButton) view;
  97.  
  98. if (bluetoothAdapter == null) {
  99. // Device does not support Bluetooth
  100. Toast.makeText(getApplicationContext(), "Oop! Your device does not support Bluetooth",
  101. Toast.LENGTH_SHORT).show();
  102. toggleButton.setChecked(false);
  103. } else {
  104.  
  105. if (toggleButton.isChecked()){ // to turn on bluetooth
  106. if (!bluetoothAdapter.isEnabled()) {
  107. // A dialog will appear requesting user permission to enable Bluetooth
  108. Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  109. startActivityForResult(enableBluetoothIntent, ENABLE_BT_REQUEST_CODE);
  110. } else {
  111. Toast.makeText(getApplicationContext(), "Your device has already been enabled." +
  112. "n" + "Scanning for remote Bluetooth devices...",
  113. Toast.LENGTH_SHORT).show();
  114. // To discover remote Bluetooth devices
  115. discoverDevices();
  116. // Make local device discoverable by other devices
  117. makeDiscoverable();
  118.  
  119. ListeningThread t = new ListeningThread();
  120. t.start();
  121.  
  122.  
  123. }
  124. } else { // Turn off bluetooth
  125.  
  126. bluetoothAdapter.disable();
  127. adapter.clear();
  128. Toast.makeText(getApplicationContext(), "Your device is now disabled.",
  129. Toast.LENGTH_SHORT).show();
  130. }
  131. }
  132. }
  133.  
  134. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  135.  
  136. if (requestCode == ENABLE_BT_REQUEST_CODE) {
  137.  
  138. // Bluetooth successfully enabled!
  139. if (resultCode == Activity.RESULT_OK) {
  140. Toast.makeText(getApplicationContext(), "Ha! Bluetooth is now enabled." +
  141. "n" + "Scanning for remote Bluetooth devices...",
  142. Toast.LENGTH_SHORT).show();
  143.  
  144. // Make local device discoverable by other devices
  145. makeDiscoverable();
  146.  
  147. // To discover remote Bluetooth devices
  148. discoverDevices();
  149.  
  150. } else { // RESULT_CANCELED as user refused or failed to enable Bluetooth
  151. Toast.makeText(getApplicationContext(), "Bluetooth is not enabled.",
  152. Toast.LENGTH_SHORT).show();
  153.  
  154. // Turn off togglebutton
  155. toggleButton.setChecked(false);
  156. }
  157. } else if (requestCode == DISCOVERABLE_BT_REQUEST_CODE){
  158.  
  159. if (resultCode == DISCOVERABLE_DURATION){
  160. Toast.makeText(getApplicationContext(), "Your device is now discoverable by other devices for " +
  161. DISCOVERABLE_DURATION + " seconds",
  162. Toast.LENGTH_SHORT).show();
  163. } else {
  164. Toast.makeText(getApplicationContext(), "Fail to enable discoverability on your device.",
  165. Toast.LENGTH_SHORT).show();
  166. }
  167. }
  168. }
  169.  
  170. protected void discoverDevices(){
  171.  
  172. // To scan for remote Bluetooth devices
  173. if (bluetoothAdapter.startDiscovery()) {
  174. Toast.makeText(getApplicationContext(), "Discovering other bluetooth devices...",
  175. Toast.LENGTH_SHORT).show();
  176.  
  177.  
  178. } else {
  179. Toast.makeText(getApplicationContext(), "Discovery failed to start.",
  180. Toast.LENGTH_SHORT).show();
  181. }
  182. }
  183.  
  184. protected void makeDiscoverable(){
  185. // Make local device discoverable
  186. Intent discoverableIntent = new
  187. Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  188. discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION);
  189. startActivityForResult(discoverableIntent, DISCOVERABLE_BT_REQUEST_CODE);
  190. }
  191.  
  192. @Override
  193. protected void onResume() {
  194. super.onResume();
  195. // Register the BroadcastReceiver for ACTION_FOUND
  196. IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  197. this.registerReceiver(broadcastReceiver, filter);
  198.  
  199. }
  200.  
  201.  
  202.  
  203. @Override
  204. protected void onPause() {
  205. super.onPause();
  206. this.unregisterReceiver(broadcastReceiver);
  207.  
  208. }
  209.  
  210. @Override
  211. public boolean onCreateOptionsMenu(Menu menu) {
  212. // Inflate the menu; this adds items to the action bar if it is present.
  213. getMenuInflater().inflate(R.menu.bluetooth, menu);
  214. return true;
  215. }
  216.  
  217. @Override
  218. public boolean onOptionsItemSelected(MenuItem item) {
  219. // Handle action bar item clicks here. The action bar will
  220. // automatically handle clicks on the Home/Up button, so long
  221. // as you specify a parent activity in AndroidManifest.xml.
  222. int id = item.getItemId();
  223. if (id == R.id.action_settings) {
  224. return true;
  225. }
  226. return super.onOptionsItemSelected(item);
  227. }
  228.  
  229. private class ListeningThread extends Thread {
  230. private final BluetoothServerSocket bluetoothServerSocket;
  231.  
  232. public ListeningThread() {
  233. BluetoothServerSocket temp = null;
  234. try {
  235. temp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(getString(R.string.app_name), uuid);
  236.  
  237. } catch (IOException e) {
  238. e.printStackTrace();
  239. }
  240. bluetoothServerSocket = temp;
  241. }
  242.  
  243. public void run() {
  244. BluetoothSocket bluetoothSocket;
  245. // This will block while listening until a BluetoothSocket is returned
  246. // or an exception occurs
  247. while (true) {
  248. try {
  249. bluetoothSocket = bluetoothServerSocket.accept();
  250.  
  251. } catch (IOException e) {
  252. break;
  253. }
  254. // If a connection is accepted
  255. if (bluetoothSocket != null) {
  256.  
  257. runOnUiThread(new Runnable() {
  258. public void run() {
  259. Toast.makeText(getApplicationContext(), "A connection has been accepted.",
  260. Toast.LENGTH_SHORT).show();
  261. }
  262. });
  263.  
  264. // Code to manage the connection in a separate thread
  265. /*
  266. manageBluetoothConnection(bluetoothSocket);
  267. */
  268.  
  269. try {
  270. bluetoothServerSocket.close();
  271. } catch (IOException e) {
  272. e.printStackTrace();
  273. }
  274. break;
  275. }
  276. }
  277. }
  278.  
  279. // Cancel the listening socket and terminate the thread
  280. public void cancel() {
  281. try {
  282. bluetoothServerSocket.close();
  283. } catch (IOException e) {
  284. e.printStackTrace();
  285. }
  286. }
  287. }
  288.  
  289. private class ConnectingThread extends Thread {
  290. private final BluetoothSocket bluetoothSocket;
  291. private final BluetoothDevice bluetoothDevice;
  292.  
  293.  
  294. public ConnectingThread(BluetoothDevice device) {
  295.  
  296. BluetoothSocket temp = null;
  297. bluetoothDevice = device;
  298.  
  299. // Get a BluetoothSocket to connect with the given BluetoothDevice
  300. try {
  301. temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
  302. } catch (IOException e) {
  303. e.printStackTrace();
  304. }
  305. bluetoothSocket = temp;
  306. }
  307.  
  308. public void run() {
  309. // Cancel discovery as it will slow down the connection
  310. bluetoothAdapter.cancelDiscovery();
  311.  
  312. try {
  313. // This will block until it succeeds in connecting to the device
  314. // through the bluetoothSocket or throws an exception
  315. bluetoothSocket.connect();
  316.  
  317. } catch (IOException connectException) {
  318. connectException.printStackTrace();
  319. try {
  320. bluetoothSocket.close();
  321. } catch (IOException closeException) {
  322. closeException.printStackTrace();
  323. }
  324. }
  325.  
  326. // Code to manage the connection in a separate thread
  327. /*
  328. manageBluetoothConnection(bluetoothSocket);
  329. */
  330. }
  331.  
  332. // Cancel an open connection and terminate the thread
  333. public void cancel() {
  334. try {
  335. bluetoothSocket.close();
  336. } catch (IOException e) {
  337. e.printStackTrace();
  338. }
  339. }
  340. }
  341.  
  342. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  343. xmlns:tools="http://schemas.android.com/tools"
  344. android:layout_width="match_parent"
  345. android:layout_height="match_parent"
  346. android:paddingLeft="@dimen/activity_horizontal_margin"
  347. android:paddingRight="@dimen/activity_horizontal_margin"
  348. android:paddingTop="@dimen/activity_vertical_margin"
  349. android:paddingBottom="@dimen/activity_vertical_margin"
  350. tools:context="com.csp.carservices.Bluetooth">
  351. <ToggleButton
  352. android:layout_width="wrap_content"
  353. android:layout_height="wrap_content"
  354. android:id="@+id/toggleButton"
  355. android:textOn="Bluetooth On"
  356. android:textOff="Bluetooth Off"
  357. android:onClick="onToggleClicked"
  358. android:layout_alignParentTop="true"
  359. android:layout_alignParentLeft="true"
  360. android:layout_alignParentStart="true" />
  361.  
  362. <ListView
  363. android:layout_width="wrap_content"
  364. android:layout_height="wrap_content"
  365. android:id="@+id/listView"
  366. android:layout_centerHorizontal="true"
  367. android:layout_below="@+id/toggleButton" />
  368.  
  369.  
  370. </RelativeLayout>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement