Я не знаю, как решить мою проблему. Как правило, приложение в BluetoothActivity включает, позволяет обнаруживать, обнаруживать и связывать с устройствами. (Он работает с наушниками, но с HC-06 сопряжен, и все) Мне нужна идея, как вызывать мой Сервис в HomeActivity, потому что я не могу забыть о действиях в течение жизненного цикла. Экран BluetoothActivity:
https://imgur.com/yfGU5qZ
Экран HomeActivity:
https://imgur.com/zTlqAGD
Я создал MyBluetoothService, который я написал, используя несколько руководств от yt. Там у меня есть темы - Connect, Accept, Connected. После того, как я щелкну устройство списка, я должен соединиться и перейти к HomeActivity (думаю, для этого мне следует использовать Intent), где 6 текстовых обзоров должны получить информацию от подключенного Arduino с HC-06.
Код BluetoothActivity:
public class BluetoothActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private static final String TAG = "Parking System";
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ArrayList<BluetoothDevice> btDevices = new ArrayList<>();
public ArrayList<BluetoothDevice> pairedBtDevices = new ArrayList<>();
public Set<BluetoothDevice> pairedDevices;
public DevicesAdapter devicesAdapter;
BluetoothAdapter bluetoothAdapter;
MyBluetoothService myBluetoothService;
private ListView listView, listView2;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
listView = (ListView)findViewById(R.id.list_devices);
listView2 = (ListView)findViewById(R.id.list_no_paired_devices);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(broadcastReceiver4,filter);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
listView.setOnItemClickListener(BluetoothActivity.this);
listView2.setOnItemClickListener(BluetoothActivity.this);
if (bluetoothAdapter==null){
Toast.makeText(getApplicationContext(),"Bluetooth is not avaible for this device !",Toast.LENGTH_SHORT).show();
finish();
}
if (!bluetoothAdapter.isEnabled()){
Log.d(TAG,"Bluetooth enaibling");
makeDiscoverable();
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBtIntent);
IntentFilter intent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(broadcastReceiver, intent);
}
showPairedDevice();
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
}
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.bluetooth_activity_menu,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.refresh:
Log.d(TAG,"MenuItem Refresh: Clicked");
Log.d(TAG,"MenuItem Refresh: Removing paired devices from list");
pairedBtDevices.removeAll(pairedBtDevices);
Log.d(TAG,"MenuItem Refresh: Removing all unpaired devices from list");
btDevices.removeAll(btDevices);
Log.d(TAG,"MenuItem Refresh: invoking showPairedDevice() method");
showPairedDevice();
Log.d(TAG,"MenuItem Refresh: Looking for unpaired devices");
if(bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
Log.d(TAG,"MenuItem Refresh: Canceled Discovery");
bluetoothAdapter.startDiscovery();
Log.d(TAG,"MenuItem Refresh: Started discovery");
checkBtPermissions();
IntentFilter discoverDevicesIntent = new IntentFilter((BluetoothDevice.ACTION_FOUND));
registerReceiver(broadcastReceiver3,discoverDevicesIntent);
}
if(!bluetoothAdapter.isDiscovering()){
checkBtPermissions();
bluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter((BluetoothDevice.ACTION_FOUND));
registerReceiver(broadcastReceiver3,discoverDevicesIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(bluetoothAdapter.ACTION_STATE_CHANGED)){
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,bluetoothAdapter.ERROR);
switch (state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG,"BroadcastReceive: OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG,"BroadcastReceive: Turning OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG,"BroadcastReceive: ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG,"BroadcastReceive: Turning ON");
break;
}
}
}
};
private final BroadcastReceiver broadcastReceiver2 = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)){
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE,BluetoothAdapter.ERROR);
switch(mode){
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d(TAG,"BroadcastReceiver2: Discoverability enabled");
break;
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d(TAG,"BroadcastReceiver2: Discoverability enable. Ready to receive connections");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d(TAG,"BroadcastReceiver2: Discovering disabled. Is not ready to receive connections");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d(TAG,"BroadcastReceiver2: Connecting...");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d(TAG,"BroadcastReceiver2: Connected !");
break;
}
}
}
};
private BroadcastReceiver broadcastReceiver3 = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG,"OnReceive: Action found");
if(action.equals(BluetoothDevice.ACTION_FOUND)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d(TAG, "Adding " + device + "to btDevices");
btDevices.add(device);
Log.d(TAG,"Paired Devices: " + pairedBtDevices + "Device: " + device);
if(pairedBtDevices.size()>0){
for(BluetoothDevice pairedDevice : pairedDevices){
Log.d(TAG,"Paired Devices: Foreach " + pairedDevice);
Log.d(TAG, "Paired Devices: Check value " + pairedDevice.equals(device));
if(pairedDevice.equals(device)){
btDevices.remove(device);
Log.d(TAG, "Removed " + device + "from btDevices");
}
}
}
Log.d(TAG, "OnReceive: " + device.getName() + " | " + device.getAddress());
devicesAdapter = new DevicesAdapter(context, R.layout.device_list_adapter_view, btDevices);
listView2.setAdapter(devicesAdapter);
}
}
};
private final BroadcastReceiver broadcastReceiver4 = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(device.getBondState()==BluetoothDevice.BOND_BONDED){
Log.d(TAG,"BroadcastReceiver4: BOND_BONDED");
Toast.makeText(getApplicationContext(),"Connected with: "+device.getName(),Toast.LENGTH_SHORT).show();
Log.d(TAG,"BroadcastReceiver4: Invoking btDeviceConnection() method");
//btDeviceConnection(device,MY_UUID);
}
if(device.getBondState()==BluetoothDevice.BOND_BONDING){
Log.d(TAG,"BroadcastReceiver4: BOND_BONDING");
}
if(device.getBondState()==BluetoothDevice.BOND_NONE){
Log.d(TAG,"BroadcastReceiver4: BOND_NONE");
}
}
}
};
public void makeDiscoverable(){
Log.d(TAG, "MakeDiscoverable: Making a device discoverable for 300 sec");
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(bluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(broadcastReceiver2,intentFilter);
}
private void showPairedDevice() {
pairedDevices = bluetoothAdapter.getBondedDevices();
Log.d(TAG,"ShowPairedDevice: Removing all paired devices from list");
pairedBtDevices.removeAll(pairedDevices);
Log.d(TAG,"ShowPairedDevice: Showing all paired devices");
if(pairedDevices.size()>0){
for(BluetoothDevice device : pairedDevices){
pairedBtDevices.add(device);
}
devicesAdapter = new DevicesAdapter(getApplicationContext(),R.layout.device_list_adapter_view,pairedBtDevices);
}
listView.setAdapter(devicesAdapter);
}
public void checkBtPermissions(){
if(Build.VERSION.SDK_INT>Build.VERSION_CODES.JELLY_BEAN_MR2){
int permCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permCheck+=this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if(permCheck!=0){
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},1001);
}
else{
Log.d(TAG,"CheckBtPermission: Need to check permissions. Your SDK < JELLY_BEAN_MR2");
}
}
}
/*
private void btDeviceConnection(BluetoothDevice device,UUID uuid){
Log.d(TAG,"BtDeviceConnection: Started");
myBluetoothService.startClient(device,uuid);
}
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
Log.d(TAG,"OnItemClick: Clicked a device");
String deviceName = btDevices.get(position).getName();
String deviceAddress = btDevices.get(position).getAddress();
Log.d(TAG,"OnItemClick: Device name: "+deviceName);
Log.d(TAG,"OnItemClick: Device address: "+deviceAddress);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
Log.d(TAG,"Trying to pair with: " + deviceName);
Toast.makeText(getApplicationContext(),"Trying to pair with: " + deviceName,Toast.LENGTH_SHORT).show();
btDevices.get(position).createBond();
}
}
@Override
protected void onDestroy() {
Log.d(TAG,"OnDestroy: Destroying");
super.onDestroy();
if(bluetoothAdapter !=null){
bluetoothAdapter.cancelDiscovery();
}
unregisterReceiver(broadcastReceiver);
unregisterReceiver(broadcastReceiver2);
unregisterReceiver(broadcastReceiver3);
unregisterReceiver(broadcastReceiver4);
}
MyBluetoothService code:
public class MyBluetoothService{
private static final String TAG = "Parking System";
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private final BluetoothAdapter bluetoothAdapter;
Context context;
private Handler handler;
private AcceptThread insecureAcceptThread;
private ConnectThread connectThread;
private BluetoothDevice bluetoothDevice;
private UUID deviceUUID;
private ProgressDialog progressDialog;
private ConnectedThread connectedThread;
public MyBluetoothService(Context context) {
this.context = context;
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
start();
}
private class AcceptThread extends Thread{
private final BluetoothServerSocket bluetoothServerSocket;
public AcceptThread(){
BluetoothServerSocket tmp = null;
try {
tmp = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("Patking System",MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothServerSocket = tmp;
}
@Override
public void run() {
Log.d(TAG, "Run: AcceptThread Running");
BluetoothSocket bluetoothSocket = null;
try {
bluetoothSocket= bluetoothServerSocket.accept();
Log.d(TAG,"Run: Accepted connection");
} catch (IOException e) {
Log.e(TAG,"AcceptThread: IOException: " + e.getMessage());
}
/*if(bluetoothSocket!=null){
connected(bluetoothSocket,blue)
}*/
}
public void cancel(){
Log.d(TAG,"Cancel: Canceling AcceptThread");
try{
bluetoothServerSocket.close();
}catch (IOException e){
Log.e(TAG,"Cancel: AcceptThread ServerSocket's error: "+e.getMessage());
}
}
}
private class ConnectThread extends Thread {
private BluetoothSocket bluetoothSocket;
public ConnectThread(BluetoothDevice device,UUID uuid) {
Log.d(TAG,"ConnectThread: Started");
bluetoothDevice = device;
deviceUUID = uuid;
}
@Override
public void run() {
BluetoothSocket tmp = null;
Log.d(TAG,"Run: ConnectThread ");
try{
Log.d(TAG,"ConnectThread: Create RfcomSocket using UUID");
tmp = bluetoothDevice.createRfcommSocketToServiceRecord(deviceUUID);
}catch (IOException e){
Log.e(TAG,"ConnectThread: Could not create RfcommSocket: "+e.getMessage());
}
bluetoothSocket=tmp;
bluetoothAdapter.cancelDiscovery();
try {
bluetoothSocket.connect();
Log.d(TAG,"Run: ConnectThread connected");
} catch (IOException e) {
try{
bluetoothSocket.close();
Log.d(TAG,"Run: Closed socket");
}catch (IOException e2){
Log.e(TAG,"Run: Can not to close connection in socket " + e2.getMessage());
}
Log.d(TAG,"Run: ConnectThread: Could not connect to UUID");
}
connected(bluetoothSocket,bluetoothDevice);
}
public void cancel(){
try{
Log.d(TAG,"Cancel: Closing client socket");
bluetoothSocket.close();
}catch (IOException e){
Log.e(TAG,"Cancel of close() : bluetoothSocket in ConnectThread failed: "+e.getMessage());
}
}
}
public synchronized void start(){
Log.d(TAG,"Start");
if(connectThread != null){
connectThread.cancel();
connectThread=null;
}
if(insecureAcceptThread==null){
insecureAcceptThread = new AcceptThread();
insecureAcceptThread.start();
}
}
private class ConnectedThread extends Thread{
private final BluetoothSocket bluetoothSocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public ConnectedThread(BluetoothSocket socket){
Log.d(TAG,"ConnectedThread: Starting");
bluetoothSocket=socket;
InputStream tmpInput = null;
OutputStream tmpOutput = null;
progressDialog.dismiss();
try{
tmpInput = bluetoothSocket.getInputStream();
tmpOutput = bluetoothSocket.getOutputStream();
}catch (IOException e){
e.printStackTrace();
}
inputStream=tmpInput;
outputStream=tmpOutput;
}
@Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while(true){
try {
bytes = inputStream.read(buffer);
String comingMsg = new String(buffer,0,bytes);
Log.d(TAG,"InputStream: " + comingMsg);
}catch (IOException e){
Log.e(TAG,"Write: Error reading input." + e.getMessage());
break;
}
}
}
public void write(byte[] bytes){
String text = new String(bytes, Charset.defaultCharset());
Log.d(TAG,"Write: Writing to outputStream: " + text);
try{
outputStream.write(bytes);
}catch (IOException e){
Log.e(TAG,"Write: Error writing to output " + e.getMessage());
}
}
public void cancel(){
try{
bluetoothSocket.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
private void connected(BluetoothSocket bluetoothSocket, BluetoothDevice bluetoothDevice) {
Log.d(TAG, "Connected: Starting");
connectedThread = new ConnectedThread(bluetoothSocket);
connectedThread.start();
}
public void write(byte[] out){
ConnectedThread r;
Log.d(TAG,"Write: Write called");
connectedThread.write(out);
}
public void startClient(BluetoothDevice device,UUID uuid){
Log.d(TAG,"StartClient: Started");
progressDialog = ProgressDialog.show(context,"Connecting Bluetooth","Please wait...",true);
connectThread = new ConnectThread(device,uuid);
connectThread.start();
}
}
HomeActivity код:
https://pastebin.com/raw/JAXGW40e
Дополнительно вы можете проверить мой код, потому что я хочу кое-чему научиться.