0% found this document useful (0 votes)
25 views6 pages

Android BT

The document contains an Android application code that establishes a Bluetooth connection to a specified device and allows sending messages over Bluetooth. It includes classes for connecting to the Bluetooth device, handling input and output streams, and managing UI interactions. The app features a button to send a predefined message and a text view to display information about the connection status.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views6 pages

Android BT

The document contains an Android application code that establishes a Bluetooth connection to a specified device and allows sending messages over Bluetooth. It includes classes for connecting to the Bluetooth device, handling input and output streams, and managing UI interactions. The app features a button to send a predefined message and a text view to display information about the connection status.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

package com.example.

myapplication;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.os.Bundle;
import android.widget.Toast;
import android.widget.EditText;

import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.util.Set;
import java.util.UUID;
import android.os.Bundle;

import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Looper;

@RequiresApi(api = Build.VERSION_CODES.M)
public class MainActivity extends AppCompatActivity {

Button btn1;
TextView txt1;
EditText edtxt;
int i=0;
String msg;

BluetoothAdapter mBluetoothAdapter;
BluetoothDevice mDevice;
BluetoothSocket bluetoothSocket;
static private UUID aUUID=UUID.fromString("00001101-0000-1000-8000-
00805F9B34FB");
final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION,
100);

void send_bt_byte(byte b)
{
try {
OutputStream bt_out = bluetoothSocket.getOutputStream();
bt_out.write(b);
//print_system_msg("sended..");
} catch (IOException e) {
e.printStackTrace();
}

}
void println_bt(String str)
{
char[] c;
c=str.toCharArray();

for(int i=0;i!=c.length;i++)
{
send_bt_byte((byte) c[i]);

}
send_bt_byte((byte) '\n');

////////////////////////////////////////////////////////////////////// connect
thread.. /////////////////////////////////////////////////////
class ConnectThread extends Thread {

private final BluetoothSocket mmSocket;


private final BluetoothDevice mmDevice;

private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-


00805F9B34FB");

@SuppressLint("MissingPermission")
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;

mmDevice = device;

try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);

} catch (IOException e) {

mmSocket = tmp;
}

@SuppressLint("MissingPermission")
public void run() {
mBluetoothAdapter.cancelDiscovery();

try {
mmSocket.connect();
print_system_msg(String.valueOf(mmSocket.isConnected()));
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException)
{
}
return;
}
}

public void cancel() {


try {
mmSocket.close();
} catch (IOException e) { }
}

}
///////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////// connected
thread ..///////////////////////////////////////////////////////////////
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;

public ConnectedThread(BluetoothSocket socket) {


mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}

public void run() {


byte[] buffer = new byte[1024];
int begin = 0;
int bytes = 0;

while (true) {
try {
bytes += mmInStream.read(buffer, bytes, buffer.length - bytes);
for(int i = begin; i < bytes; i++) {
if(buffer[i] == "#".getBytes()[0]) {
mHandler.obtainMessage(1, begin, i,
buffer).sendToTarget();
begin = i + 1;
if(i == bytes - 1) {
bytes = 0;
begin = 0;
}
}
}
} catch (IOException e) {
break;
}
}
}

}
///////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////
HANDLE //////////////////////////////////////////

@SuppressLint("HandlerLeak")
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
byte[] writeBuf = (byte[]) msg.obj;
int begin = (int)msg.arg1;
int end = (int)msg.arg2;

switch(msg.what) {
case 1:
String writeMessage = new String(writeBuf);
writeMessage = writeMessage.substring(begin, end);
print_system_msg(writeMessage);
tg.startTone(ToneGenerator.TONE_CDMA_HIGH_PBX_L,200);
//tg.release();
break;
}
}
};

///////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////
void print_system_msg(String str)
{
Toast.makeText(getApplicationContext(), str,Toast.LENGTH_SHORT).show();

@SuppressLint("MissingPermission")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=(Button) findViewById(R.id.run1);
txt1=(TextView) findViewById(R.id.textView1);
edtxt=(EditText )findViewById(R.id.intxt);

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

if (mBluetoothAdapter == null)
{
print_system_msg("Disabled..");
}

if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
print_system_msg("Enabled..");

try {
mDevice=mBluetoothAdapter.getRemoteDevice("98:D3:31:F6:B4:D6");
bluetoothSocket=mDevice.createRfcommSocketToServiceRecord(aUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
bluetoothSocket.connect();
print_system_msg(String.valueOf(bluetoothSocket.isConnected()));

} catch (IOException e) {
e.printStackTrace();
}

ConnectedThread mConnectedThread = new ConnectedThread(bluetoothSocket);


mConnectedThread.start();

btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
println_bt("Hello..");

}
});

txt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
i = 0;
txt1.setText(String.valueOf(i));

}
});

}
}

You might also like