Advertisement
Guest User

ConnectClient

a guest
Sep 8th, 2013
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.52 KB | None | 0 0
  1. package com.example.PollClient;
  2.  
  3. import android.app.Activity;
  4. import android.app.AlertDialog;
  5. import android.bluetooth.BluetoothAdapter;
  6. import android.bluetooth.BluetoothDevice;
  7. import android.bluetooth.BluetoothSocket;
  8. import android.content.DialogInterface;
  9. import android.content.Intent;
  10. import android.os.Bundle;
  11. import android.util.Log;
  12. import android.view.View;
  13. import android.widget.Button;
  14. import android.widget.EditText;
  15. import android.widget.TextView;
  16. import android.widget.ViewFlipper;
  17.  
  18. import java.io.*;
  19. import java.util.UUID;
  20.  
  21. /**
  22.  * Created with IntelliJ IDEA.
  23.  * User: Sean
  24.  * Date: 9/7/13
  25.  * Time: 2:49 PM
  26.  * To change this template use File | Settings | File Templates.
  27.  */
  28. public class Connection extends Activity {
  29.     private static final String DEBUG = "DEBUG_LOG";
  30.     private static final int REQUEST_ENABLE_BT = 1;
  31.  
  32.     private static final int GET_MESSAGE = 0;
  33.     private static final int SEND_MESSAGE = 1;
  34.     private int CUR_STATE;
  35.  
  36.     private BluetoothAdapter btAdapter = null;
  37.     private BluetoothSocket btSocket = null;
  38.     private Intent intent;
  39.  
  40.     private InputStream inStream = null;
  41.     private BufferedReader bReader = null;
  42.     private OutputStream outputStream = null;
  43.     private PrintWriter printWriter = null;
  44.  
  45.     private EditText macAddress;
  46.     private Button macButton;
  47.     private Button connectButton;
  48.  
  49.     // Well known SPP UUID
  50.     private static final UUID MY_UUID =
  51.             UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  52.  
  53.     //    // Insert your server's MAC address
  54.     private static String address = "78:DD:08:A3:F3:3F";
  55.  
  56.     /** Called when the activity is first created. */
  57.     @Override
  58.     public void onCreate(Bundle savedInstanceState) {
  59.         super.onCreate(savedInstanceState);
  60.         setContentView(R.layout.connect);
  61.  
  62.         CUR_STATE = GET_MESSAGE;
  63.  
  64.         Log.d(DEBUG,"\n...Connect In onCreate()...");
  65.         btAdapter = BluetoothAdapter.getDefaultAdapter();
  66.         CheckBTState();
  67.  
  68.         macAddress = (EditText) findViewById(R.id.editText);
  69.         macAddress.setText(address);
  70.  
  71.         macButton = (Button) findViewById(R.id.saveMACButton);
  72.         macButton.setOnClickListener(new View.OnClickListener() {
  73.             @Override
  74.             public void onClick(View v) {
  75.                 address = macAddress.getText().toString();
  76.             }
  77.         });
  78.  
  79.         connectButton = (Button) findViewById(R.id.connectButton);
  80.         connectButton.setOnClickListener(new View.OnClickListener() {
  81.             @Override
  82.             public void onClick(View v) {
  83.                 try{
  84.                     connectClient();
  85.                 } catch (IOException e){
  86.                     e.printStackTrace();
  87.                 }
  88.             }
  89.         });
  90.     }
  91.  
  92.     private void CheckBTState() {
  93.         // Check for Bluetooth support and then check to make sure it is turned on
  94.  
  95.         // Emulator doesn't support Bluetooth and will return null
  96.         if(btAdapter==null) {
  97.             AlertBox("Fatal Error", "Bluetooth Not supported. Aborting.");
  98.         } else {
  99.             if (btAdapter.isEnabled()) {
  100.                 Log.d(DEBUG, "\n...Bluetooth is enabled...");
  101.             } else {
  102.                 //Prompt user to turn on Bluetooth
  103.                 Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
  104.                 startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
  105.             }
  106.         }
  107.     }
  108.  
  109.     public void AlertBox( String title, String message ){
  110.         new AlertDialog.Builder(this)
  111.                 .setTitle( title )
  112.                 .setMessage( message + " Press OK to exit." )
  113.                 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
  114.                     public void onClick(DialogInterface arg0, int arg1) {
  115.                         finish();
  116.                     }
  117.                 }).show();
  118.     }
  119.  
  120.     private void connectClient() throws IOException {
  121.         //Get the String JSON Message and store it for the poll activity
  122.         Log.d(DEBUG, "\n...Attempting client connect...");
  123.  
  124.         // Hard coded connection for now
  125.         // Set up a pointer to the remote node using it's address.
  126.         BluetoothDevice device = btAdapter.getRemoteDevice(address);
  127.  
  128.         // Two things are needed to make a connection:
  129.         //   A MAC address, which we got above.
  130.         //   A Service ID or UUID.  In this case we are using the
  131.         //     UUID for SPP.
  132.         try {
  133.             btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
  134.         } catch (IOException e) {
  135.             AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
  136.         }
  137.  
  138.         // Discovery is resource intensive.  Make sure it isn't going on
  139.         // when you attempt to connect and pass your message.
  140.         btAdapter.cancelDiscovery();
  141.  
  142.         // Establish the connection.  This will block until it connects.
  143.         try {
  144.             btSocket.connect();
  145.             Log.d(DEBUG, "\n...Connection established and data link opened...");
  146.         } catch (IOException e) {
  147.             try {
  148.                 btSocket.close();
  149.             } catch (IOException e2) {
  150.                 AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
  151.             }
  152.         }
  153.  
  154.         getMessage();
  155.         intent = new Intent(Connection.this, PollTaker.class);
  156.         startActivity(intent);
  157.     }
  158.  
  159.     private void getMessage() throws IOException{
  160.         Log.d(DEBUG, "\n Getting Message");
  161.  
  162.         try{
  163.             inStream = btSocket.getInputStream();
  164.             bReader = new BufferedReader(new InputStreamReader(inStream));
  165.             String message = bReader.readLine();
  166.  
  167.             CUR_STATE = SEND_MESSAGE;
  168.             //Get the String JSON Message and store it for the poll activity
  169.         } catch (IOException e){
  170.             AlertBox("Fatal Error", "In onResume() and input stream creation failed:" + e.getMessage() + ".");
  171.         }
  172.     }
  173.  
  174.     private void sendMessage(){
  175.         Log.d(DEBUG, "\n Sending Message");
  176.         try {
  177.             outputStream = btSocket.getOutputStream();
  178.             printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
  179.  
  180.             //Get JSON Response object, push
  181.             CUR_STATE = GET_MESSAGE;
  182.         } catch (IOException e) {
  183.             AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
  184.         }
  185.     }
  186. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement