Check bluetooth connection android

How to check bluetooth connection state with paired device in Android

I develop an bluetooth app which will connect to a paired device and send a message, but I have to test connection before. I’ve tried many options, but nothing works in good way. So could you send me any example of code which can do it? I made an thread, but I can’t get an good state of connection to build an «if» function. Here is the code:

package com.example.szukacz; import java.lang.reflect.Method; import java.util.Set; import android.app.Activity; 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.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity < LinearLayout sparowaneUrzadzenia; public void lokalizowanie() < Intent intencja = new Intent(this, Lokalizator.class); startActivity(intencja); >public void parowanie(View v) < Intent intencja = new Intent(this, Parowanie.class); startActivity(intencja); >boolean isRunning; Handler handler = new Handler() < @Override public void handleMessage(Message msg) < String status = (String)msg.obj; if(status == "polaczony") < alarm(); showToast("prawda, zwraca" + status); >else < showToast("wykonanie x, zwraca: " + status); >; > >; public void alarm() < showToast("Alarm. "); >@Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sparowaneUrzadzenia = (LinearLayout) findViewById(R.id.listaUrzadzenGlowna); pokazSparowane(); >public void onStop() < super.onStop(); isRunning = false; >public void onStart() < super.onStart(); Thread testPolaczen = new Thread(new Runnable() < public void run() < try < for(int i = 0; i < 1000000; i++) < Thread.sleep(5000); testujPolaczenia(); int stan = 0; String status = Integer.toString(stan); Message msg = handler.obtainMessage(1, (String)status); if(isRunning == true) < handler.sendMessage(msg); >> > catch (Throwable t) < // watek stop >> >); isRunning = true; testPolaczen.start(); > private void testujPolaczenia() < >public void pokazSparowane() < /* * Wyświetlanie listy sparowanych urządzeń . * */ Log.d("INFO","Sparowane dla tego urzÄ…dzenia"); BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); SetpairedDevices = mBluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) < for (BluetoothDevice device : pairedDevices) < Log.d("INFO",device.getName()+" - "+device.getAddress()); // dodawanie urzadzen do listy Button urzadzenie = new Button(getApplicationContext()); urzadzenie.setText(device.getName()); // urzadzenie.setTextColor(0xffffff); //jak ustawic na czarny kolor napsisów ? urzadzenie.setOnClickListener(new OnClickListener() < @Override public void onClick(View v) < showToast("klik"); lokalizowanie(); >>); sparowaneUrzadzenia.addView(urzadzenie); > > else < showToast("brak sparowanych urzadzen"); >> @Override public boolean onCreateOptionsMenu(Menu menu) < // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; >private void showToast(String message) < Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); >@Override public boolean onOptionsItemSelected(MenuItem item) < // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int if (id == R.id.action_settings) < return true; >return super.onOptionsItemSelected(item); > > 

Источник

Читайте также:  Cyber brand retail драйвера bluetooth адаптер

How to check if a bluetooth device is connected with Android device?

This example demonstrates how do I check if a Bluetooth device is connected with android device.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Step 3 − Add the following code to src/MainActivity.java

import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity < @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); this.registerReceiver(broadcastReceiver, filter); >private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() < BluetoothDevice device; @Override public void onReceive(Context context, Intent intent) < String action = intent.getAction(); device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) < Toast.makeText(getApplicationContext(), "Device is now Connected", Toast.LENGTH_SHORT).show(); >else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) < Toast.makeText(getApplicationContext(), "Device is disconnected", Toast.LENGTH_SHORT).show(); >> >; >

Step 4 − Add the following code to androidManifest.xml

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project’s activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Источник

Android: How to detect Bluetooth connection status

You need to implement BluetoothProfile.ServiceListener :

BluetoothProfile.ServiceListener b = new BlueToothListener(); boolean profileProxy = BluetoothAdapter.getDefaultAdapter() .getProfileProxy(Handler.bot, b, BluetoothProfile.HEADSET); public class BlueToothListener implements ServiceListener < public static BluetoothHeadset headset; public static BluetoothDevice bluetoothDevice; @Override public void onServiceDisconnected(int profile) @Override public void onServiceConnected(int profile, BluetoothProfile proxy) NEVER List connectedDevices = proxy .getConnectedDevices(); for (BluetoothDevice device : connectedDevices) < Debugger.log("BluetoothDevice found :" + device); bluetoothDevice = device; int connectionState = headset.getConnectionState(bluetoothDevice); Debugger.log("BluetoothHeadset connectionState "+connectionState);//2 == OK boolean startVoiceRecognition = headset .startVoiceRecognition(device); if (startVoiceRecognition) < Debugger .log("BluetoothHeadset init Listener OK"); return; >else Notify.popup("Bluetooth headset can't start speech recognition"); > > catch (Exception e) < // >> > > 

Monitoring of the BT status can be done indeed by polling. Here’s how I did it (full sample here) . Note that it’s just a sample and you should manage the polling better:

implementation 'androidx.core:core-ktx:1.9.0' implementation 'com.google.android.material:material:1.7.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation "androidx.work:work-runtime-ktx:2.7.1" 

MainActivityViewModel.kt

@UiThread class MainActivityViewModel(application: Application) : BaseViewModel(application) < private val bluetoothAdapter: BluetoothAdapter = context.getSystemService(). adapter private var bluetoothHeadsetProfile: BluetoothProfile? = null val connectedDevicesLiveData = DistinctLiveDataWrapper(MutableLiveData(ConnectedDevicesState.Idle)) val bluetoothTurnedOnLiveData = DistinctLiveDataWrapper(MutableLiveData(null)) val isConnectedToBtHeadsetLiveData = DistinctLiveDataWrapper(MutableLiveData(null)) private val pollingBtStateRunnable: Runnable init < updateBtStates() pollingBtStateRunnable = object : Runnable < override fun run() < updateBtStates() handler.postDelayed(this, POLLING_TIME_IN_MS) >> // Establish connection to the proxy. val serviceListener = object : BluetoothProfile.ServiceListener < override fun onServiceConnected(profile: Int, bluetoothProfile: BluetoothProfile) < this@MainActivityViewModel.bluetoothHeadsetProfile = bluetoothProfile handler.removeCallbacks(pollingBtStateRunnable) pollingBtStateRunnable.run() >override fun onServiceDisconnected(profile: Int) < handler.removeCallbacks(pollingBtStateRunnable) updateBtStates() >> bluetoothAdapter.getProfileProxy(context, serviceListener, BluetoothProfile.HEADSET) onClearedListeners.add < this.bluetoothHeadsetProfile?.let < bluetoothProfile ->bluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, bluetoothProfile) > handler.removeCallbacks(pollingBtStateRunnable) > > fun initWithLifecycle(lifecycle: Lifecycle) < lifecycle.addObserver(object : DefaultLifecycleObserver < override fun onResume(owner: LifecycleOwner) < super.onResume(owner) pollingBtStateRunnable.run() >override fun onPause(owner: LifecycleOwner) < super.onPause(owner) handler.removeCallbacks(pollingBtStateRunnable) >>) > @UiThread private fun updateBtStates() < // Log.d("AppLog", "updateBtStates") val isBlueToothTurnedOn = bluetoothAdapter.state == BluetoothAdapter.STATE_ON bluetoothTurnedOnLiveData.value = isBlueToothTurnedOn if (!isBlueToothTurnedOn) < connectedDevicesLiveData.value = ConnectedDevicesState.BluetoothIsTurnedOff isConnectedToBtHeadsetLiveData.value = false return >val isConnectedToBtHeadset = try < bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET) == BluetoothAdapter.STATE_CONNECTED >catch (e: SecurityException) < null >isConnectedToBtHeadsetLiveData.value = isConnectedToBtHeadset val bluetoothProfile = bluetoothHeadsetProfile if (bluetoothProfile != null) < if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) < val connectedDevicesSet = bluetoothProfile.connectedDevices.toHashSet() val previousConnectedDevices = (connectedDevicesLiveData.value as? ConnectedDevicesState.GotResult)?.connectedDevices if (previousConnectedDevices == null || previousConnectedDevices != connectedDevicesSet) connectedDevicesLiveData.value = ConnectedDevicesState.GotResult(connectedDevicesSet) >else < connectedDevicesLiveData.value = ConnectedDevicesState.NeedBlueToothConnectPermission >> else < connectedDevicesLiveData.value = ConnectedDevicesState.Idle >> companion object < private const val POLLING_TIME_IN_MS = 500L >> 

MainActivity.kt

class MainActivity : AppCompatActivity() < private lateinit var viewModel: MainActivityViewModel override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) viewModel = ViewModelProvider(this)[MainActivityViewModel::class.java] viewModel.initWithLifecycle(lifecycle) viewModel.bluetoothTurnedOnLiveData.observe(this) < Log.d("AppLog", "MainActivity bluetoothTurnedOnLiveData BT turned on? $it") >viewModel.isConnectedToBtHeadsetLiveData.observe(this) < Log.d("AppLog", "MainActivity isConnectedToBtHeadsetLiveData BT headset connected? $it") >viewModel.connectedDevicesLiveData.observe(this) < Log.d("AppLog", "MainActivity connectedDevicesLiveData devices: $it") >findViewById(R.id.grantBtPermission).setOnClickListener < if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) < requestPermissions(arrayOf(Manifest.permission.BLUETOOTH_CONNECT), 1) >> > > 

ConnectedDevicesState.kt

sealed class ConnectedDevicesState < object Idle : ConnectedDevicesState() < override fun toString(): String < if (BuildConfig.DEBUG) return "Idle" return super.toString() >> class GotResult(@Suppress("MemberVisibilityCanBePrivate") val connectedDevices: Set) : ConnectedDevicesState() < override fun toString(): String < if (BuildConfig.DEBUG) < return "GotResult: connectedDevices:$< connectedDevices.map < try < it.name >catch (e: SecurityException) < it.address >> >" > return super.toString() > > object BluetoothIsTurnedOff : ConnectedDevicesState() < override fun toString(): String < if (BuildConfig.DEBUG) return "BluetoothIsTurnedOff" return super.toString() >> object NeedBlueToothConnectPermission : ConnectedDevicesState() < override fun toString(): String < if (BuildConfig.DEBUG) return "NeedBlueToothConnectPermission" return super.toString() >> > 

DistinctLiveDataWrapper.kt

class DistinctLiveDataWrapper(@Suppress("MemberVisibilityCanBePrivate") val mutableLiveData: MutableLiveData) < @Suppress("MemberVisibilityCanBePrivate") val distinctLiveData = Transformations.distinctUntilChanged(mutableLiveData) var value: T? @UiThread set(value) < mutableLiveData.value = value >get() < return mutableLiveData.value >@AnyThread fun postValue(value: T) < mutableLiveData.postValue(value) >fun observe(lifecycleOwner: LifecycleOwner, observer: Observer) < distinctLiveData.observe(lifecycleOwner, observer) >> 

BaseViewModel.kt

/**usage: class MyViewModel(application: Application) : BaseViewModel(application) * getting instance: private lateinit var viewModel: MyViewModel * viewModel=ViewModelProvider(this).get(MyViewModel::class.java)*/ abstract class BaseViewModel(application: Application) : AndroidViewModel(application) < @Suppress("MemberVisibilityCanBePrivate") var isCleared = false @Suppress("MemberVisibilityCanBePrivate") val onClearedListeners = ArrayList() @Suppress("unused") @SuppressLint("StaticFieldLeak") val context: Context = application.applicationContext @Suppress("unused") val handler = Handler(Looper.getMainLooper()) override fun onCleared() < super.onCleared() isCleared = true onClearedListeners.forEach < it.run() >> > 

Источник

Читайте также:  Bose bluetooth soundlink leather

How to check if bluetooth is enabled programmatically?

I would like to check if bluetooth is enabled on any Android device periodically. Is there any intents that I could catch using BroadcastReceiver to do so, or is there other ways to do it?

7 Answers 7

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) < // Device does not support Bluetooth >else if (!mBluetoothAdapter.isEnabled()) < // Bluetooth is not enabled :) >else < // Bluetooth is enabled >

nope, you don’t need internet to check bluetooth status. well, aside from getting the code from this SO post 😉

public boolean isBluetoothEnabled()

with the permission in manifest file:

Here I have other alternative as an answer for this question.

First add following lines in your Manifest file.

Now, where you want to check Bluetooth supportability, use following code.

boolean isBluetoothSupported = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH); 

To check Bluetooth state, ON or OFF, programmatically:

 BluetoothAdapter btAdapter = ((Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) ?((BluetoothManager)mContext.getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter() :(BluetoothAdapter.getDefaultAdapter())); if(btAdapter==null) < return; >if(btAdapter.getState()==BluetoothAdapter.STATE_ON) < //Bluetooth is ON >

You may also listen to Intent action:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED 

for check bt disconnected

mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_DISCONNECTED 

Источник

How to programmatically check connection state of a Bluetooth device in Android?

It has the method to get the bond state of the remote device, and possible values for the bond state are: BOND_NONE , BOND_BONDING , BOND_BONDED . But it’s not the connection state.

The method can be used to get the connection state, but the BluetoothProfile object must be obtained first.

public abstract int getConnectionState (BluetoothDevice device); 

As describe in doc: «Clients should call getProfileProxy(Context, BluetoothProfile.ServiceListener, int), to get the Profile Proxy.«, it can ONLY be retrieve in a ServiceListener called when state changes.

Читайте также:  Киа рио подключить телефон через блютуз

What if I query the state on startup without any state changes happen yet?

public int getConnectionState (BluetoothDevice device, int profile); 

But it cannot be used to detect connection state of a Bluetooth speaker, as the profile argument only accepts GATT or GATT_SERVER (for low energy device), other profiles ( HEADSET , HEALTH , A2DP ) are not supported.

public int getProfileConnectionState (int profile); 

This function can be used to check whether the local Bluetooth adapter is connected to any remote device for a specific profile. It can be used to check a specified profile. But it cannot be used to check a given device.

Does anyone know how to get the connection state of a given Bluetooth device?

Источник

Оцените статью
Adblock
detector