, кажется, работает на телефонах Samsung после перезагрузки, но не на разных производителях. < /P>
работает на: < /p>
- < / /и br />
Samsung S23 (Android 13) < /li>
Samsung S23 Ultra (Android 14) < /li>
< /ul>
Это не работает на < /p>
Google Pixel 6A (Android 13) < /li>
. 13) - OnePlus 8 Pro (Android 13)
Я представил услугу переднего плана, которая начинается после перезагрузки устройства, а затем закрывается вскоре после вскоре. Это была попытка убедиться, что приложение активировано после Reboot. Интересно, что это действие вызвало всплывающий метод службы компаньона. Тем не менее, это должно произойти без необходимости вручную подключаться к устройству через настройки Bluetooth на телефоне.
Код: Выделить всё
...
...
...
< /code>
Код для ассоциации устройства из документации Google: < /p>
private const val SELECT_DEVICE_REQUEST_CODE = 0
class MainActivity : AppCompatActivity() {
private val deviceManager: CompanionDeviceManager by lazy {
getSystemService(Context.COMPANION_DEVICE_SERVICE) as CompanionDeviceManager
}
val mBluetoothAdapter: BluetoothAdapter by lazy {
val java = BluetoothManager::class.java
getSystemService(java)!!.adapter }
val executor: Executor = Executor { it.run() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// To skip filters based on names and supported feature flags (UUIDs),
// omit calls to setNamePattern() and addServiceUuid()
// respectively, as shown in the following Bluetooth example.
val deviceFilter: BluetoothDeviceFilter = BluetoothDeviceFilter.Builder()
.setNamePattern(Pattern.compile("My device"))
.addServiceUuid(ParcelUuid(UUID(0x123abcL, -1L)), null)
.build()
// The argument provided in setSingleDevice() determines whether a single
// device name or a list of them appears.
val pairingRequest: AssociationRequest = AssociationRequest.Builder()
.addDeviceFilter(deviceFilter)
.setSingleDevice(true)
.build()
// When the app tries to pair with a Bluetooth device, show the
// corresponding dialog box to the user.
deviceManager.associate(pairingRequest,
executor,
object : CompanionDeviceManager.Callback() {
// Called when a device is found. Launch the IntentSender so the user
// can select the device they want to pair with.
override fun onAssociationPending(intentSender: IntentSender) {
intentSender?.let {
startIntentSenderForResult(it, SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0)
}
}
override fun onAssociationCreated(associationInfo: AssociationInfo) {
// AssociationInfo object is created and get association id and the
// macAddress.
var associationId: int = associationInfo.id
var macAddress: MacAddress = associationInfo.deviceMacAddress
}
override fun onFailure(errorMessage: CharSequence?) {
// Handle the failure.
}
)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
SELECT_DEVICE_REQUEST_CODE -> when(resultCode) {
Activity.RESULT_OK -> {
// The user chose to pair the app with a Bluetooth device.
val deviceToPair: BluetoothDevice? =
data?.getParcelableExtra(CompanionDeviceManager.EXTRA_DEVICE)
deviceToPair?.let { device ->
deviceManager?.startObservingDevicePresence(device.address)
}
}
}
else -> super.onActivityResult(requestCode, resultCode, data)
}
}
}
< /code>
companionservice.kt:
@RequiresApi(Build.VERSION_CODES.S)
class CompanionService : CompanionDeviceService() {
override fun onCreate() {
super.onCreate()
Timber.d("Companion - onCreate")
}
override fun onUnbind(intent: Intent?): Boolean {
Timber.d("Companion - onUnbind")
return super.onUnbind(intent)
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
override fun onDeviceAppeared(associationInfo: AssociationInfo) {
Timber.d("Companion - onDeviceAppeared")
}
@Deprecated("Deprecated in Java")
override fun onDeviceAppeared(address: String) {
Timber.d("Companion - onDeviceAppeared")
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
override fun onDeviceDisappeared(associationInfo: AssociationInfo) {
Timber.d("Companion - onDeviceDisappeared")
}
@Deprecated("Deprecated in Java")
override fun onDeviceDisappeared(address: String) {
Timber.d("Companion - onDeviceDisappeared")
}
override fun onDestroy() {
Timber.d("Companion - onDestroy")
super.onDestroy()
}
}
Подробнее здесь: https://stackoverflow.com/questions/783 ... thle-devic