Advertisement
shashiskills

Untitled

Oct 29th, 2012
1,935
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.06 KB | None | 0 0
  1. package com.kant.bluetoothtesting;
  2.  
  3. import java.io.IOException;
  4. import java.io.OutputStream;
  5. import java.io.OutputStreamWriter;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import java.util.Set;
  9. import java.util.UUID;
  10.  
  11. import android.app.Activity;
  12. import android.bluetooth.BluetoothAdapter;
  13. import android.bluetooth.BluetoothDevice;
  14. import android.bluetooth.BluetoothSocket;
  15. import android.content.BroadcastReceiver;
  16. import android.content.Context;
  17. import android.content.Intent;
  18. import android.content.IntentFilter;
  19. import android.os.Bundle;
  20. import android.view.KeyEvent;
  21. import android.view.View;
  22. import android.widget.AdapterView;
  23. import android.widget.ArrayAdapter;
  24. import android.widget.Button;
  25. import android.widget.ListView;
  26. import android.widget.Toast;
  27.  
  28. public class BluetoothTestActivity extends Activity {
  29.  private static final int REQUEST_ENABLE_BT = 243;
  30.  @Override
  31.  protected void onResume() {
  32.   connector=null;
  33.   check=false;
  34.   super.onResume();
  35.  }
  36.  
  37.  @Override
  38.  protected void onStop() {
  39.   connector.cancel();
  40.   super.onStop();
  41.  }
  42.  
  43.  private Set<bluetoothdevice> pairedDevices = null;
  44.  private BluetoothAdapter mbluetoothAdapter = null;
  45.  
  46.  private Button bPaired = null;
  47.  private Button bDiscover = null;
  48.  private Button bStopDiscovery = null;
  49.  private Button bRemote=null;
  50.  private Button bForward = null;
  51.  private Button bBackward = null;
  52.  
  53.  private ArrayAdapter<item> mpArrayAdpater = null;
  54.  private ArrayAdapter<item> mdArrayAdpater = null;
  55.  private ListView pairedList = null;
  56.  private ListView discoveredList = null;
  57.  
  58.  private List<item> pSet = null;
  59.  private List<item> dSet = null;
  60.  private boolean check = false;
  61.  
  62.  private ConnectThread connector = null;
  63.  
  64.  private BroadcastReceiver mReceiver = new BroadcastReceiver() {
  65.  
  66.   @Override
  67.   public void onReceive(Context context, Intent intent) {
  68.    String action = intent.getAction();
  69.    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  70.     BluetoothDevice device = intent
  71.       .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  72.     Item item = new Item(device.getName(), device);
  73.     mdArrayAdpater.add(item);
  74.    }
  75.   }
  76.  };
  77.  
  78.  @Override
  79.  public void onCreate(Bundle savedInstanceState) {
  80.   super.onCreate(savedInstanceState);
  81.   setContentView(R.layout.main);
  82.  
  83.   bPaired = (Button) findViewById(R.id.bPaired);
  84.   bDiscover = (Button) findViewById(R.id.bDiscover);  
  85.   bStopDiscovery=(Button)findViewById(R.id.bStop);
  86.  
  87.   //these three to control slide motion
  88.   bRemote=(Button)findViewById(R.id.bRemote);
  89.   bForward = (Button) findViewById(R.id.bFwd);
  90.   bBackward = (Button) findViewById(R.id.bBack);
  91.  
  92.  
  93.  
  94.   pairedList = (ListView) findViewById(R.id.listPaired);
  95.   discoveredList = (ListView) findViewById(R.id.listDiscovered);
  96.  
  97.   pSet = new ArrayList<item>();
  98.   dSet = new ArrayList<item>();
  99.  
  100.   mpArrayAdpater = new ArrayAdapter<item>(getApplicationContext(),
  101.     android.R.layout.simple_list_item_1, pSet);
  102.   mdArrayAdpater = new ArrayAdapter<item>(getApplicationContext(),
  103.     android.R.layout.simple_list_item_1, dSet);
  104.  
  105.   pairedList.setAdapter(mpArrayAdpater);
  106.   discoveredList.setAdapter(mdArrayAdpater);
  107.  
  108.   // Get Bluetooth device and enable it if not enabled
  109.   mbluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  110.   if (mbluetoothAdapter == null) {
  111.    Toast.makeText(getApplicationContext(),
  112.      "device donot support bluetooth ", Toast.LENGTH_LONG)
  113.      .show();
  114.   }
  115.  
  116.   if (!mbluetoothAdapter.isEnabled()) {
  117.    Intent enableIntent = new Intent(
  118.      BluetoothAdapter.ACTION_REQUEST_ENABLE);
  119.    startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
  120.   }
  121.  
  122.   // Button's onclickListener
  123.   bPaired.setOnClickListener(new View.OnClickListener() {
  124.  
  125.    @Override
  126.    public void onClick(View v) {
  127.     pairedDevices = mbluetoothAdapter.getBondedDevices();
  128.     if (pairedDevices.size() &gt; 0) {
  129.      for (BluetoothDevice bdevice : pairedDevices) {
  130.       Item item = new Item(bdevice.getName(), bdevice);
  131.       mpArrayAdpater.add(item);
  132.      }
  133.     }
  134.  
  135.    }
  136.   });
  137.  
  138.   bDiscover.setOnClickListener(new View.OnClickListener() {
  139.  
  140.    @Override
  141.    public void onClick(View v) {
  142.     IntentFilter filter = new IntentFilter(
  143.       BluetoothDevice.ACTION_FOUND);
  144.     registerReceiver(mReceiver, filter);
  145.     mdArrayAdpater.clear();
  146.     mbluetoothAdapter.startDiscovery();
  147.    }
  148.   });
  149.  
  150.   bRemote.setText("Start");
  151.   bRemote.setOnClickListener(new View.OnClickListener() {
  152.  
  153.    @Override
  154.    public void onClick(View v) {
  155.     if (check == true) {
  156.      bRemote.setText("Stop");
  157.      check = false;
  158.     } else {
  159.      bRemote.setText("Start");
  160.      if (connector != null)
  161.       connector.cancel();
  162.      check=true;
  163.     }
  164.    }
  165.   });
  166.  
  167.   bForward.setOnClickListener(new View.OnClickListener() {
  168.  
  169.    @Override
  170.    public void onClick(View v) {
  171.     OutputStream out = null;
  172.     try {
  173.      if (check == false) {
  174.       out = connector.getMmSocket().getOutputStream();
  175.       out.write(2);
  176.      }
  177.     } catch (IOException e) {
  178.      // TODO Auto-generated catch block
  179.      e.printStackTrace();
  180.     }
  181.    }
  182.   });
  183.  
  184.   bBackward.setOnClickListener(new View.OnClickListener() {
  185.  
  186.    @Override
  187.    public void onClick(View v) {
  188.     OutputStream out = null;
  189.     try {
  190.      if (check == false) {
  191.       out = connector.getMmSocket().getOutputStream();
  192.       out.write(3);
  193.      }
  194.     } catch (IOException e) {
  195.      // TODO Auto-generated catch block
  196.      e.printStackTrace();
  197.     }
  198.    }
  199.   });
  200.  
  201.   bStopDiscovery.setOnClickListener(new View.OnClickListener() {
  202.  
  203.    @Override
  204.    public void onClick(View v) {
  205.     mbluetoothAdapter.cancelDiscovery();
  206.    }
  207.   });
  208.  
  209.   /*
  210.    * to make your device discoverable Intent discoverableIntent = new
  211.    * Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  212.    * discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
  213.    * startActivity(discoverableIntent);
  214.    */
  215.  
  216.   // listView onItemClickListeners
  217.   pairedList
  218.     .setOnItemClickListener(new AdapterView.OnItemClickListener() {
  219.  
  220.      @Override
  221.      public void onItemClick(AdapterView parent, View view,
  222.        int position, long id) {
  223.       Item item = (Item) parent.getAdapter()
  224.         .getItem(position);
  225.       String texte = item.getDevName() + " "
  226.         + item.getBdevice().getAddress();
  227.       Toast.makeText(getApplicationContext(), texte,
  228.         Toast.LENGTH_SHORT).show();
  229.      }
  230.     });
  231.  
  232.   discoveredList
  233.     .setOnItemClickListener(new AdapterView.OnItemClickListener() {
  234.  
  235.      @Override
  236.      public void onItemClick(AdapterView parent, View view,
  237.        int position, long id) {
  238.       Item item = (Item) parent.getAdapter()
  239.         .getItem(position);
  240.       String texte = item.getDevName() + " "
  241.         + item.getBdevice().getAddress();
  242.       Toast.makeText(getApplicationContext(), texte,
  243.         Toast.LENGTH_SHORT).show();
  244.  
  245.       //If without disconnecting one tries to connect again
  246.       if(connector!=null)connector.cancel();
  247.       check=false;
  248.       bRemote.setText("Start");
  249.       //----------------------------------------------------
  250.      
  251.       mbluetoothAdapter.cancelDiscovery();
  252.       connector = new ConnectThread(item.getBdevice());
  253.       connector.start();
  254.       try {
  255.        Thread.sleep(2000, 0);
  256.       } catch (InterruptedException e) {
  257.        // TODO Auto-generated catch block
  258.        e.printStackTrace();
  259.       }      
  260.       Toast.makeText(getApplicationContext(), "now start", Toast.LENGTH_SHORT).show();
  261.      }
  262.     });
  263.  }
  264.  
  265.  @Override
  266.  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  267.   // TODO Auto-generated method stub
  268.   super.onActivityResult(requestCode, resultCode, data);
  269.   if (resultCode == RESULT_OK &amp;&amp; requestCode == REQUEST_ENABLE_BT) {
  270.    Toast.makeText(getApplicationContext(),
  271.      "Bluetooth enabled perfectly", Toast.LENGTH_SHORT).show();
  272.   }
  273.  }
  274.  
  275.  // Needed for Adpater to able store more info and to have a proper view of
  276.  // B-devices
  277.  class Item {
  278.   String devName;
  279.   BluetoothDevice bdevice;
  280.  
  281.   public Item(String devName, BluetoothDevice bdevice) {
  282.    super();
  283.    this.devName = devName;
  284.    this.bdevice = bdevice;
  285.   }
  286.  
  287.   public String getDevName() {
  288.    return devName;
  289.   }
  290.  
  291.   public void setDevName(String devName) {
  292.    this.devName = devName;
  293.   }
  294.  
  295.   public BluetoothDevice getBdevice() {
  296.    return bdevice;
  297.   }
  298.  
  299.   public void setBdevice(BluetoothDevice bdevice) {
  300.    this.bdevice = bdevice;
  301.   }
  302.  
  303.   @Override
  304.   public String toString() {
  305.    // TODO Auto-generated method stub
  306.    return this.getDevName();
  307.   }
  308.  }
  309.  
  310.  class ConnectThread extends Thread {
  311.   private final BluetoothSocket mmSocket;
  312.   private final BluetoothDevice mmDevice;
  313.  
  314.   public ConnectThread(BluetoothDevice device) {
  315.    // Use a temporary object that is later assigned to mmSocket,
  316.    // because mmSocket is final
  317.    BluetoothSocket tmp = null;
  318.    mmDevice = device;
  319.  
  320.    // Get a BluetoothSocket to connect with the given BluetoothDevice
  321.    try {
  322.     // MY_UUID is the app's UUID string, also used by the server
  323.     // code
  324.     UUID uuid = UUID
  325.       .fromString("0f2b61c1-8be2-40e6-ab90-e735818da0a7");
  326.     tmp = mmDevice.createRfcommSocketToServiceRecord(uuid);
  327.  
  328.    } catch (IOException e) {
  329.    }
  330.    mmSocket = tmp;
  331.   }
  332.  
  333.   public void run() {
  334.    // Cancel discovery because it will slow down the connection
  335.    try {
  336.     // Connect the device through the socket. This will block
  337.     // until it succeeds or throws an exception
  338.     mmSocket.connect();
  339.    } catch (IOException connectException) {
  340.     // Unable to connect; close the socket and get out
  341.     try {
  342.      mmSocket.close();
  343.     } catch (IOException closeException) {
  344.     }
  345.     return;
  346.    }
  347.  
  348.    // Do work to manage the connection (in a separate thread)
  349.    manageConnectedSocket(mmSocket);
  350.   }
  351.  
  352.   private void manageConnectedSocket(BluetoothSocket mmSocket2) {
  353.    //to get things start working set to true
  354.    check = true;
  355.   }
  356.  
  357.   public BluetoothSocket getMmSocket() {
  358.    return mmSocket;
  359.   }
  360.  
  361.   // Will cancel an in-progress connection, and close the socket
  362.   public void cancel() {
  363.    try {
  364.     mmSocket.close();
  365.    } catch (IOException e) {
  366.    }
  367.   }
  368.  }
  369. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement