Skip to content

Java Code for Android

Adit Kabra edited this page Jun 15, 2013 · 1 revision

package com.example.connecttest;

import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.UUID;

import android.app.Activity; import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView;

import com.example.bttest.R;

public class ConnectTest extends Activity { TextView out; private static final int REQUEST_ENABLE_BT = 1; private BluetoothAdapter btAdapter = null; private BluetoothSocket btSocket = null; private OutputStream outStream = null; Button up; Button down;

// Well known SPP UUID static String x="00001101-0000-1000-8000-00805f9b34fb"; private static final UUID MY_UUID = UUID.fromString(x);

// Insert your server's MAC address private static String address = "84:A6:C8:0F:00:0E";

/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

out = (TextView) findViewById(R.id.out);
up = (Button) findViewById (1256);
down = (Button) findViewById (R.id.down);
 
out.append("\n...In onCreate()...");

btAdapter = BluetoothAdapter.getDefaultAdapter();
CheckBTState();

}

@Override public void onStart() { super.onStart(); out.append("\n...In onStart()..."); }

@Override public void onResume() { super.onResume(); //out.append("\n...In onResume...\n...Attempting client connect..."); // Set up a pointer to the remote node using it's address. BluetoothDevice device = btAdapter.getRemoteDevice(address);

// Two things are needed to make a connection:
//   A MAC address, which we got above.
//   A Service ID or UUID.  In this case we are using the
//     UUID for SPP.
try {
  btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
  AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}

// Discovery is resource intensive.  Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();

// Establish the connection.  This will block until it connects.
try {
  btSocket.connect();
  out.append("\n...Connection established and data link opened...");
} catch (IOException e) {
  try {
    btSocket.close();
  } catch (IOException e2) {
    AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
  }
}

// Create a data stream so we can talk to server.
out.append("\n...Sending message to server...");

DataOutputStream dos = null;
try {
  outStream = btSocket.getOutputStream();
  dos = new DataOutputStream(outStream);
} catch (IOException e) {
  AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}

String message = "Hello from Android.\n";
byte[] msgBuffer = message.getBytes();

try {
  outStream.write(msgBuffer);
  dos.writeChar('H');
  dos.writeChar('i');
} catch (IOException e) {
  String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
  if (address.equals("00:00:00:00:00:00")) 
    msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
  msg = msg +  ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
   
  AlertBox("Fatal Error", msg);       
}

out.append(".\n....data link opened...");

try{ 
	up.setOnClickListener (new View.OnClickListener() {
		
		String message2 = "up";
	    byte[] msgBuffer2 = message2.getBytes();
	
	@Override
	public void onClick(View v) {
		myFancyMethod(v);
		//out.append(".\n....button clicked...");
	}

	public void myFancyMethod(View v) {
		// TODO Auto-generated method stub
		try {
			outStream.write(msgBuffer2);
			//out.append(".\n....up is taken...");				
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}		
});
        }
finally{

}

try{ 
	down.setOnClickListener (new View.OnClickListener() {
		
		String message3 = "down";
	    byte[] msgBuffer3 = message3.getBytes();
	
	@Override
	public void onClick(View v) {
		myFancyMethod2(v);
		//out.append(".\n....button clicked...");
	}

	public void myFancyMethod2(View v) {
		// TODO Auto-generated method stub
		try {
			outStream.write(msgBuffer3);
			//out.append(".\n....up is taken...");				
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}		
});
        }
finally{

} } @Override public void onPause() { super.onPause();

out.append("\n...In onPause()...");

if (outStream != null) {
  try {
    outStream.flush();
  } catch (IOException e) {
    AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
  }
}

try     {
  btSocket.close();
} catch (IOException e2) {
  AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}

}

@Override public void onStop() { super.onStop(); out.append("\n...In onStop()..."); }

@Override public void onDestroy() { super.onDestroy(); out.append("\n...In onDestroy()..."); }

private void CheckBTState() { // Check for Bluetooth support and then check to make sure it is turned on

// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) { 
  AlertBox("Fatal Error", "Bluetooth Not supported. Aborting.");
} else {
  if (btAdapter.isEnabled()) {
    out.append("\n...Bluetooth is enabled...");
  } else {
    //Prompt user to turn on Bluetooth
    Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
  }
}

}

public void AlertBox( String title, String message ){ new AlertDialog.Builder(this) .setTitle( title ) .setMessage( message + " Press OK to exit." ) .setPositiveButton("OK", new OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { finish(); } }).show(); } }

Clone this wiki locally