어찌저찌 인터넷자료들을 참고하여 아두이노 보드와 블루투스 통신을하는 코드는 어영부영 짜기는했습니다. 그래서 특정블루투스 신호를 받으면 핸드폰에서 알림을 띄우고 싶었는데 Thread안에서는 알림을 띄울수 없다고 하더라구요... 이게 mainactivity.java에서 다음과같이 thread를 실행시키고
package com.example.testapplication;
import androidx.annotation.UiThread;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
String TAG = "MainActivity";
UUID BT_MODULE_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // "random" unique identifier
TextView textStatus;
Button btnParied, btnSearch, btnSend;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> pairedDevices;
ArrayAdapter<String> btArrayAdapter;
ArrayList<String> deviceAddressArray;
private final static int REQUEST_ENABLE_BT = 1;
BluetoothSocket btSocket = null;
ConnectedThread connectedThread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get permission
String[] permission_list = {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
};
ActivityCompat.requestPermissions(MainActivity.this, permission_list, 1);
...
// start bluetooth communication
if(flag){
textStatus.setText("connected to "+name);
connectedThread = new ConnectedThread(btSocket, MainActivity.this);
connectedThread.start();
}
}
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class);
return (BluetoothSocket) m.invoke(device, BT_MODULE_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
return device.createRfcommSocketToServiceRecord(BT_MODULE_UUID);
}
}
이 밑의 코드가 ConnectedThread.java파일입니다.
package com.example.testapplication;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private Context mcontext = null;
public ConnectedThread(BluetoothSocket socket, Context context) {
mmSocket = socket;
this.mcontext = context;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
@Override
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.available();
if (bytes != 0) {
buffer = new byte[1024];
SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
bytes = mmInStream.available(); // how many bytes are ready to be read?
bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
AlertDialog.Builder builder = new AlertDialog.Builder(mcontext);
builder.setTitle("Title");
builder.setMessage("Context");
builder.setPositiveButton("Yes", null);
builder.setNegativeButton("No", null);
builder.setNeutralButton("Cancel", null);
builder.create().show();
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String input) {
byte[] bytes = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(bytes);
} catch (IOException e) {
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
여기 run()내부에서 블루투스 신호를 읽어들이면 Alertdialog를 띄우려고했는데 에러로 앱이 뻗어버리더군요 ㅠㅠㅠ... 3~4시간동안 구글링을 동원해보았지만 Handler를 사용해야한다는것 같은데 감이 잡히질 않습니다. 도와주시며 정말 감사드리겠습니다.