Java Android-蓝牙广播接收器有20秒延迟

Java Android-蓝牙广播接收器有20秒延迟,java,android,bluetooth,Java,Android,Bluetooth,我正在尝试编写一个简单的应用程序,在Spotify检测到与特定蓝牙耳机的连接后开始播放音乐。 下面的代码正在工作,但广播接收器在20秒后被激活。是否可以在连接后立即执行此操作,或者我应该使用其他方法?我看到了一些关于BluetoothAdapter的东西,但我不知道如何使用它 Service.java public class Service extends BroadcastReceiver { @Override public void onReceive(Context context,

我正在尝试编写一个简单的应用程序,在Spotify检测到与特定蓝牙耳机的连接后开始播放音乐。 下面的代码正在工作,但广播接收器在20秒后被激活。是否可以在连接后立即执行此操作,或者我应该使用其他方法?我看到了一些关于BluetoothAdapter的东西,但我不知道如何使用它

Service.java

public class Service extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    // Toast.makeText(context,"Teraz",Toast.LENGTH_LONG).show();
    String action = intent.getAction();
    if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        if (device.getName().equals("MDR-XB650BT")) {
            String spotifyPackageName = "com.spotify.music";
            String viewAction = Intent.ACTION_VIEW;
            String spotifyUriString = "spotify:user:spotify:playlist:37i9dQZF1DXasrwGQyyDvl" + ":play";
            Uri spotifyUri = Uri.parse(spotifyUriString);
            Intent spotifyIntent = new Intent(viewAction, spotifyUri);
            //I found this in other questions, but it doesn't work for me
            spotifyIntent.setFlags(FLAG_RECEIVER_FOREGROUND | FLAG_ACTIVITY_BROUGHT_TO_FRONT | FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_PREVIOUS_IS_TOP);
            intent.setFlags(FLAG_RECEIVER_FOREGROUND | FLAG_ACTIVITY_BROUGHT_TO_FRONT | FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_PREVIOUS_IS_TOP);
            spotifyIntent.setPackage(spotifyPackageName);
            if (spotifyIntent != null) {
                context.startActivity(spotifyIntent);//null pointer check in case package name was not found
            }
        }
    }
}
}

AndroidManifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.pawe.bluetooth_service"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name">


    <receiver android:name=".Service">
        <intent-filter android:priority="999">
            <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
            <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
        </intent-filter>
    </receiver>

    <activity android:name=".hello">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>