You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android 12中CompanionDeviceService创建后立即销毁的问题

Android 12 CompanionDeviceService 启动后立即销毁问题

我开发了一个简易Activity,调用指定函数会显示BLE配对请求。用户确认配对后,调用startObservingDevicePresence("Some Mac address"),成功触发CompanionDeviceService,日志显示设备已进入范围,但紧接着服务就执行了onDestroy方法。应用仍正常运行且日志无报错信息。有人成功使用过这些Android 12新API吗?


MainActivity 代码

public class MainActivity extends ReactActivity {
    private static final int SELECT_DEVICE_REQUEST_CODE = 42;
    private static CompanionDeviceManager deviceManager;
    private static AssociationRequest pairingRequest;
    private static BluetoothDeviceFilter deviceFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(null);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            deviceManager = getSystemService(CompanionDeviceManager.class);
        }
    }

    public void start() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            deviceFilter = new BluetoothDeviceFilter.Builder()
                    .build();

            pairingRequest = new AssociationRequest.Builder()
                    .addDeviceFilter(deviceFilter)
                    .build();

            deviceManager.associate(pairingRequest,
                    new CompanionDeviceManager.Callback() {
                        @Override
                        public void onDeviceFound(IntentSender chooserLauncher) {
                            try {
                                startIntentSenderForResult(chooserLauncher,
                                        SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0);
                            } catch (IntentSender.SendIntentException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(CharSequence charSequence) {

                        }
                    },
                    null);

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                try {
                    deviceManager.startObservingDevicePresence("Some MAC address");
                } catch(DeviceNotAssociatedException e) {}
            }
        }
    }
}

BleCompanionDeviceService 代码

@RequiresApi(VERSION_CODES.S)
public class BleCompanionDeviceService extends CompanionDeviceService {
    private static final String TAG = "BleReceiver";

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDeviceAppeared(@NonNull String s) {
        Log.d(TAG, "DEVICE APPEARED INTO RANGE");
    }

    @Override
    public void onDeviceDisappeared(@NonNull String s) {
        Log.d(TAG, "DEVICE DISAPPEARED");
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "SERVICE DESTROYED");
    }
}

排查与解决方向

  1. 检查Service注册配置
    确保AndroidManifest.xml中正确注册服务,且添加必要的intent filter:

    <service
        android:name=".BleCompanionDeviceService"
        android:exported="true">
        <intent-filter>
            <action android:name="android.companion.CompanionDeviceService" />
        </intent-filter>
    </service>
    

    android:exported必须设为true,否则系统无法调用该服务。

  2. 验证设备关联有效性
    调用startObservingDevicePresence前,先通过deviceManager.getAssociatedDevices()确认目标MAC地址对应的设备已成功关联。硬编码MAC地址容易出错,建议从onActivityResult的返回数据中获取设备标识符:

    BluetoothDevice device = data.getParcelableExtra(CompanionDeviceManager.EXTRA_DEVICE);
    String validDeviceId = device.getAddress();
    deviceManager.startObservingDevicePresence(validDeviceId);
    
  3. 确认权限齐全
    确保Manifest中声明并动态申请了以下权限:

    • BLUETOOTH_SCAN
    • BLUETOOTH_CONNECT
    • ACCESS_FINE_LOCATION(Android 12+用于BLE扫描)
  4. 避免服务被系统回收
    若应用进程优先级较低,系统可能回收服务。可在BleCompanionDeviceService的onCreate中调用startForeground()提升优先级(注意Android 12+的前台服务通知要求),或确保应用拥有后台运行权限。

内容的提问来源于stack exchange,提问作者Deddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 10:45:34