Advertisement
Guest User

BT_java_sample01

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