Skip to content

Instantly share code, notes, and snippets.

@rhaseven7h
Last active August 12, 2018 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhaseven7h/b7c144507e40406b54e4ee903010b6ec to your computer and use it in GitHub Desktop.
Save rhaseven7h/b7c144507e40406b54e4ee903010b6ec to your computer and use it in GitHub Desktop.
AyncTask for Bluetooth on Android
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="@+id/btnRelay1On"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="@string/relay_1_on"
android:textAllCaps="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btnRelay2On"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="@string/relay_2_on"
android:textAlignment="center"
android:textAllCaps="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnRelay1Off" />
<Button
android:id="@+id/btnRelay1Off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="@string/relay_1_off"
android:textAllCaps="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnRelay1On" />
<Button
android:id="@+id/btnRelay2Off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="@string/relay_2_off"
android:textAlignment="center"
android:textAllCaps="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnRelay2On" />
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
class SomeClass {
public void SomeMethod() {
Class<?> clazz = bluetoothSocket.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[]{Integer.TYPE};
@SuppressWarnings("JavaReflectionMemberAccess")
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[]{1};
bluetoothSocket = (BluetoothSocket) m.invoke(bluetoothSocket.getRemoteDevice(), params);
}
}
package gmedina.wedev.tk.purebluetoothtestforhc05;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.AsyncTask;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class AsyncBluetoothComm extends AsyncTask<String, Void, Void> {
private final static String TAG = AsyncBluetoothComm.class.getSimpleName();
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Log.i(TAG, "Somehow this thing finished...");
}
@Override
protected void onProgressUpdate(Void... voids) {
super.onProgressUpdate(voids);
}
@Override
protected Void doInBackground(String... commands) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
List<BluetoothDevice> bluetoothDeviceList = new ArrayList<>();
BluetoothDevice bluetoothDevice;
for (BluetoothDevice currentDevice : bluetoothAdapter.getBondedDevices()) {
if (currentDevice.getName().startsWith("Rha7Bt")) {
bluetoothDeviceList.add(currentDevice);
}
}
if (bluetoothDeviceList.size() == 0)
throw new RuntimeException("No Rha7Bt devices available!");
bluetoothDevice = bluetoothDeviceList.get(0);
Log.i(TAG, bluetoothDevice.getName());
BluetoothSocket bluetoothSocket;
try {
bluetoothSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString("62285383-deab-4616-c932-e09c7f3d7793"));
bluetoothSocket.connect();
} catch (IOException e) {
try {
//noinspection JavaReflectionMemberAccess
Method createRfcommSocket =
bluetoothDevice
.getClass()
.getMethod(
"createRfcommSocket",
int.class
);
bluetoothSocket = (BluetoothSocket) createRfcommSocket.invoke(bluetoothDevice, 1);
bluetoothSocket.connect();
} catch (
IllegalAccessException |
NoSuchMethodException |
InvocationTargetException |
IOException e1
) {
e1.printStackTrace();
return null;
}
}
OutputStream outputStream;
InputStream inputStream;
try {
inputStream = bluetoothSocket.getInputStream();
outputStream = bluetoothSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
return null;
}
try {
outputStream.write((commands[0] + "\r\r").getBytes());
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
return null;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
try {
StringBuilder str = new StringBuilder();
while (inputStream.available() > 0) {
str.append(((char) inputStream.read()));
}
Log.i(TAG, str.toString());
} catch (IOException e) {
e.printStackTrace();
return null;
}
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return null;
}
}
package gmedina.wedev.tk.purebluetoothtestforhc05;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnRelay1On;
Button btnRelay1Off;
Button btnRelay2On;
Button btnRelay2Off;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.btnRelay1On = findViewById(R.id.btnRelay1On);
this.btnRelay1Off = findViewById(R.id.btnRelay1Off);
this.btnRelay2On = findViewById(R.id.btnRelay2On);
this.btnRelay2Off = findViewById(R.id.btnRelay2Off);
View.OnClickListener btnOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.this.buttonsOnClickHandler(v);
}
};
this.btnRelay1On.setOnClickListener(btnOnClickListener);
this.btnRelay1Off.setOnClickListener(btnOnClickListener);
this.btnRelay2On.setOnClickListener(btnOnClickListener);
this.btnRelay2Off.setOnClickListener(btnOnClickListener);
}
private void buttonsOnClickHandler(View v) {
switch (v.getId()) {
case R.id.btnRelay1On:
Toast.makeText(this, "Sending command...", Toast.LENGTH_SHORT).show();
new AsyncBluetoothComm().execute("relay 1 on");
break;
case R.id.btnRelay1Off:
Toast.makeText(this, "Sending command...", Toast.LENGTH_SHORT).show();
new AsyncBluetoothComm().execute("relay 1 off");
break;
case R.id.btnRelay2On:
Toast.makeText(this, "Sending command...", Toast.LENGTH_SHORT).show();
new AsyncBluetoothComm().execute("relay 2 on");
break;
case R.id.btnRelay2Off:
Toast.makeText(this, "Sending command...", Toast.LENGTH_SHORT).show();
new AsyncBluetoothComm().execute("relay 2 off");
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment