Advertisement
Guest User

JARLes

a guest
Jul 22nd, 2014
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.71 KB | None | 0 0
  1. package com.example.testconection;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import java.util.Set;
  7. import java.util.UUID;
  8.  
  9. import android.app.Activity;
  10. import android.bluetooth.BluetoothAdapter;
  11. import android.bluetooth.BluetoothDevice;
  12. import android.bluetooth.BluetoothSocket;
  13. import android.content.DialogInterface.OnClickListener;
  14. import android.content.Intent;
  15. import android.os.Bundle;
  16. import android.support.v7.app.ActionBarActivity;
  17. import android.view.Menu;
  18. import android.view.MenuItem;
  19. import android.view.View;
  20. import android.widget.Button;
  21. import android.widget.Toast;
  22.  
  23.  
  24. public class MainActivity extends ActionBarActivity {
  25.  
  26.     private static final UUID mUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  27.     private static final String mMacBluetooth = "XX:XX:XX:XX:XX:XX";
  28.     private final int REQUEST_ENABLE_BT = 1;
  29.  
  30.     private final String mStrBluetooth = "linvor";
  31.    
  32.     Button btSend, btRec, btConect, btDesconect;
  33.     private String mStrRec;
  34.     private String mStrSend  = "abababa";
  35.    
  36.     private BluetoothAdapter mBluetoothAdapter;
  37.     private Set<BluetoothDevice> mPairedDevices;   
  38.     private BluetoothSocket mBtSocket = null;
  39.     private OutputStream outStream = null;
  40.     private InputStream inStream = null;
  41.    
  42.     @Override
  43.     protected void onCreate(Bundle savedInstanceState) {
  44.         super.onCreate(savedInstanceState);
  45.         setContentView(R.layout.activity_main);
  46.        
  47.         //Checa se o bluetooth está disponivel
  48.         mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  49.         if(mBluetoothAdapter == null){
  50.             System.out.println("Bluetooth não está disponivel!");
  51.         }
  52.        
  53.         //Checa se o bluetooth está habilitado
  54.         if (!mBluetoothAdapter.isEnabled()) {
  55.             Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  56.             startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
  57.         }
  58.        
  59.        
  60.         btSend = (Button) findViewById(R.id.btSend);
  61.         btRec = (Button) findViewById(R.id.btRec);
  62.         btConect = (Button) findViewById(R.id.btConect);
  63.         btDesconect = (Button) findViewById(R.id.btDesconect);
  64.        
  65.         //Botão de enviar a string
  66.         btSend.setOnClickListener(new View.OnClickListener() {
  67.            
  68.             @Override
  69.             public void onClick(View v){
  70.                 //Enviando dados exemplo...
  71.                 sendData(mStrSend);
  72.             }
  73.         });
  74.         //Botão de receber a string
  75.         btRec.setOnClickListener(new View.OnClickListener() {
  76.            
  77.             @Override
  78.             public void onClick(View v){
  79.                 //Enviando dados exemplo...
  80.                 recData();
  81.             }
  82.         });
  83.         //Botão de conexão
  84.         btConect.setOnClickListener(new View.OnClickListener() {
  85.            
  86.             @Override
  87.             public void onClick(View v){
  88.                 //conecta
  89.                 conectBtArduinoWithMac();
  90.             }
  91.         });
  92.  
  93.         //Botão de desconectar
  94.         btDesconect.setOnClickListener(new View.OnClickListener() {
  95.            
  96.             @Override
  97.             public void onClick(View v){
  98.                 //desconecta
  99.                 desconectBtArduino();
  100.             }
  101.         });
  102.     }
  103.        
  104.     //Método que retorna do startActivityForResult com os códigos de resultado
  105.     protected void onActivityResult(int requestCode, int resultCode, Intent data){
  106.         super.onActivityResult(requestCode, resultCode, data);
  107.      
  108.         if(requestCode == REQUEST_ENABLE_BT){
  109.             if(resultCode == Activity.RESULT_OK){
  110.                 System.out.println("Bluetooth Ativado!");
  111.             }
  112.             else{
  113.                 System.out.println("Bluetooth nao foi ativado com sucesso!");
  114.                 finish();
  115.             }
  116.         }
  117.        
  118.         conectBtArduinoWithPareads();
  119.     }
  120.  
  121.     //Conecta-se com uso do MAC
  122.     public void conectBtArduinoWithMac(){
  123.         //Tenta se conectar a um dispositvo com MAC conhecido(do shild bluetooth)
  124.         BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mMacBluetooth);
  125.         try{
  126.             //Socket de conexao
  127.             mBtSocket = device.createRfcommSocketToServiceRecord(mUUID);
  128.             //Inicia conexão
  129.             mBtSocket.connect();
  130.         }catch(IOException e){
  131.             System.out.println("Exception gerada: " + e);
  132.         }
  133.     }
  134.  
  135.    
  136.     //Conecta-se com dispositivos já pareados
  137.     public void conectBtArduinoWithPareads(){
  138.         mPairedDevices = mBluetoothAdapter.getBondedDevices();
  139.         BluetoothDevice mDeviceBluetooth = null;
  140.        
  141.         if(mPairedDevices.size() > 0){
  142.             for(BluetoothDevice device : mPairedDevices){
  143.                 if(device.getName().equals(mStrBluetooth)){
  144.                     mDeviceBluetooth = device;
  145.                     break;
  146.                 }
  147.             }
  148.         }
  149.        
  150.         System.out.println("Dispositivo de conexao: " + mDeviceBluetooth.getName());
  151.        
  152.         try{
  153.             System.out.println("Criando socket de conexao...");
  154.             //Socket de conexao
  155.             mBtSocket = mDeviceBluetooth.createRfcommSocketToServiceRecord(mUUID);
  156.             System.out.println("Requisitando conexao...");
  157.             //Inicia conexão
  158.             mBtSocket.connect();
  159.         }catch(IOException e){
  160.             System.out.println("Exception gerada: " + e);
  161.         }
  162.     }
  163.        
  164.     //deconecta-se
  165.     public void desconectBtArduino(){
  166.         if(mBtSocket != null){
  167.             try{
  168.                 mBtSocket.close();
  169.                 mBtSocket = null;
  170.             }catch(IOException e){
  171.                 System.out.println("Exception gerada: " + e);
  172.             }
  173.         }
  174.     }
  175.  
  176.     //Envia dados    
  177.     public void sendData(String strRota){
  178.         if(mBtSocket != null){
  179.             try {
  180.                 outStream = mBtSocket.getOutputStream();
  181.             } catch (Exception e) {
  182.                 System.out.println("Exception(Send): " + e);
  183.             }
  184.            
  185.             byte[] strRotaBuffer = strRota.getBytes();
  186.             try {
  187.                 //outStream.write(strRotaBuffer);
  188.                 System.out.println("Enviando string...");
  189.                 outStream.write('a');
  190.             } catch (Exception e) {
  191.                 System.out.println("Exception(Send): " + e);
  192.             }
  193.         }
  194.         else{
  195.             System.out.println("Bluetooth nao conetado!");
  196.         }
  197.     }
  198.      
  199.     @Override
  200.     public boolean onCreateOptionsMenu(Menu menu) {
  201.         // Inflate the menu; this adds items to the action bar if it is present.
  202.         getMenuInflater().inflate(R.menu.main, menu);
  203.         return true;
  204.     }
  205.  
  206.     @Override
  207.     public boolean onOptionsItemSelected(MenuItem item) {
  208.         // Handle action bar item clicks here. The action bar will
  209.         // automatically handle clicks on the Home/Up button, so long
  210.         // as you specify a parent activity in AndroidManifest.xml.
  211.         int id = item.getItemId();
  212.         if (id == R.id.action_settings) {
  213.             return true;
  214.         }
  215.         return super.onOptionsItemSelected(item);
  216.     }
  217. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement