Android 自动 - 用户连接移动设备时回调

Android Auto - Callback when user connects mobile device

关于 Android 汽车,当用户将设备插入汽车时,我如何获得回调?我想根据用户实际连接到 android auto 的时间触发一个动作,这可能吗?

您应该可以获取 USB 连接广播。从那里你将不得不编写自己的逻辑来确定 Android Auto 在前台。 (可能需要稍微延迟一下,以防 android 自动启动需要时间。启动器似乎是 google 播放服务的一部分)

这是我在我的服务 onCreate 方法中的做法(正确的示例代码):

IntentFilter filter = new IntentFilter(CarHelper.ACTION_MEDIA_STATUS);
mCarConnectionReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String connectionEvent = intent.getStringExtra(CarHelper.MEDIA_CONNECTION_STATUS);
        mIsConnectedToCar = "media_connected".equals(connectionEvent);
        LogHelper.i(TAG, "Connection event to Android Auto: ", connectionEvent,
                " isConnectedToCar=", mIsConnectedToCar);
        if(mIsConnectedToCar ) {
            if(mService == null) {
                bindMusicService();
                if (mService != null) {
                    try {
                        initMediaMetaData();
                        toggleMediaPlaybackState(mService.isPlaying());
                    } catch (RemoteException e) {
                        Log.d(TAG, e.toString());
                    }
                }
            }
        }
    }
};
registerReceiver(mCarConnectionReceiver, filter);