Bluetooth: No broadcast for ACTION_FOUND or ACTION

2019-07-29 09:48发布

问题:

This simple broadcastreceiver never receives anything. No discovered device from BluetoothDevice and no start/stop of discovery from BluetoothAdapter.

Earlier in the code, I check that Bluetooth is enabled and the BluetoothAdapter correctly lists the three paired devices. I've tried variations of unpairing them manually in the phone and I turn bluetooth visibility in the three remote devices on and off. But nothing is logged from my broadcast receiver. I start/stop discovery with layout buttons. startDiscovery() always returns true, cancelDiscovery() always returns false. The code is basically from the Android Bluetooth Dev Guide.

My code:

package intrax.three;

import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import intrax.three.R;

public class BtAct extends Activity {
    final String TAG = "BtAct";
    final int ENABLE_BLUETOOTH_REQ = 1;
    final String[] STATENAMES = {"Disconnected","Connecting","Connected","Disconnecting","STATE UNDEFINED","STATE UNDEFINED","STATE UNDEFINED","STATE UNDEFINED","STATE UNDEFINED","STATE UNDEFINED","Off","Turning on","On","Turning off"};
long discoveryStartTime = 0;

BluetoothAdapter btAdapter;
IntentFilter intentFilter;

protected void onCreate(Bundle savedInstanceState) {
    Log.d(TAG, "onCreate");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.btlayout);

    btAdapter = BluetoothAdapter.getDefaultAdapter();

    /* Device's own Bluetooth */
    if (!btAdapter.isEnabled()) {
        Intent enableBluetoothIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBluetoothIntent, ENABLE_BLUETOOTH_REQ);
        Log.v(TAG, "The device's own bluetooth is NOT enabled.");
    }
    else {
        Log.v(TAG, "The device's own bluetooth IS enabled.");
        String  btOwnAddress =  btAdapter.getAddress();
        String  btOwnName =         btAdapter.getName();
        int         btOwnState =        btAdapter.getState();
        Log.v(TAG, btOwnAddress+" "+btOwnName);
        Log.v(TAG, STATENAMES[btOwnState]);
    }

    /** List paired devices **/
    Log.v(TAG, "Check for paired devices:");
    discoveryStartTime = SystemClock.uptimeMillis();
    Set<BluetoothDevice> allPairedDevices = btAdapter.getBondedDevices();
    Log.v(TAG, "It took "+(SystemClock.uptimeMillis()-discoveryStartTime+"ms to get paired devices. Starttime="+discoveryStartTime));
    if (allPairedDevices.size() > 0) {
        for (BluetoothDevice pairedDevice : allPairedDevices) {
            Log.v(TAG, pairedDevice.getName()+" "+pairedDevice.getAddress()+" was found");
        }
    }

    /* Remote bluetooth */
    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,0);
    startActivity(discoverableIntent);

    intentFilter = new IntentFilter();
    intentFilter.addAction("ACTION_FOUND");
    intentFilter.addAction("ACTION_DISCOVERY_STARTED");
    intentFilter.addAction("ACTION_DISCOVERY_FINISHED");

    /* User interface */
    Button bStartScan =(Button)findViewById(R.id.buttonStartScan);
    bStartScan.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Log.v(TAG, "intentReceiver="+intentReceiver);
            Log.v(TAG, "Discovery started");
            boolean bol = btAdapter.startDiscovery();
            Log.v(TAG, "Returned from discovery, start="+bol);
            Log.v(TAG, "Disc enabled="+btAdapter.isDiscovering());
        }
    });//END bStart
    Button bStopScan =(Button)findViewById(R.id.buttonStopScan);
    bStopScan.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Log.v(TAG, "bStopScan clicked");
            if (btAdapter.isDiscovering()) {
                 boolean bol = btAdapter.cancelDiscovery();
                    Log.v(TAG, "Discovery canceled="+bol);
            };
            Log.v(TAG, "still discovering="+btAdapter.isDiscovering());
        }
    });//END bStop


}//END onCreate


private BroadcastReceiver intentReceiver = new BroadcastReceiver() {  // Abstract class
    public void onReceive(Context context, Intent receivedIntent) {
        Log.v(TAG, "Entered intentReceiver");
        if (BluetoothDevice.ACTION_FOUND.equals(receivedIntent.getAction())) 
        {
            Log.v(TAG, "Found after="+(SystemClock.uptimeMillis()-discoveryStartTime));
            BluetoothDevice foundDevice = receivedIntent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Log.v(TAG, foundDevice.getName()+" "+foundDevice.getAddress()+" was found");
            BluetoothDevice foundDeviceClass = receivedIntent.getParcelableExtra(BluetoothDevice.EXTRA_CLASS);
            Log.v(TAG, "BT class: "+foundDeviceClass.toString());
        }
        else if (btAdapter.ACTION_DISCOVERY_STARTED.equals(receivedIntent.getAction())) {
            discoveryStartTime = SystemClock.uptimeMillis();
        }
        else if (btAdapter.ACTION_DISCOVERY_FINISHED.equals(receivedIntent.getAction())) {
            Log.v(TAG, "Discovery lasted: "+(SystemClock.uptimeMillis()-discoveryStartTime+"ms Starttime="+discoveryStartTime));
        }
        Log.v(TAG, "intentReceiver finished");
    }//END onReceive
};//END BroadcastReceiver

protected void onActivityResult(int requestCode, int resultCode, Intent resultIntent) {
    super.onActivityResult(requestCode, resultCode, resultIntent);
    switch(requestCode) {
    case ENABLE_BLUETOOTH_REQ:
        if(resultCode==RESULT_OK) {
            Log.v(TAG, "Bluetooth successfully enabled by request");
        }
        else {
            Log.v(TAG, "Bluetooth was not enabled. Finishing.");
            finish();
        }
    }//END switch
}//END onActivityResult

protected void onResume() {
    Log.v(TAG, "onResume");
    super.onResume();
    registerReceiver(intentReceiver, intentFilter);
    Log.v(TAG, "intentReceiver="+intentReceiver);
}

protected void onPause() {
    Log.v(TAG, "onPause");
    super.onPause();
    if (intentReceiver != null) {
        Log.v(TAG, "intentReceiver to be unregistered");
        unregisterReceiver(intentReceiver);
    }
}
}//END Class

EDIT AGAIN: Changed to:

intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

The following is logged when I click on a physical button on one of the paired remote devices (a headphone), although still nothing is logged as received. I suppose that it is some other app or the OS, it's not my app:

02-24 14:12:23.096: D/InputMethodManager(28164): dispatchKeyEvent
02-24 14:12:23.096: V/InputMethodManager(28164): DISPATCH KEY: com.android.internal.view.IInputMethodSession$Stub$Proxy@47c89938
02-24 14:12:23.156: D/InputMethodManager(28164): dispatchKeyEvent
02-24 14:12:23.156: V/InputMethodManager(28164): DISPATCH KEY: com.android.internal.view.IInputMethodSession$Stub$Proxy@47c89938

回答1:

seems like you are not registering broadcast receivers in your code:

IntentFilter intFilter = new IntentFilter();
intFilter.addAction(BluetoothDevice.ACTION_FOUND);
intFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

in your onResume:

registerReceiver(intentReceiver , intFilter);

in onPause:

unregisterReceiver(intentReceiver);


回答2:

i had the same problema, follow my solution:

if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction()) && sBluetoothAdapter.isDiscovering()) {

After i cancel my discovery and if even so the BroadcastReceiver catch BluetoothDevice.ACTION_FOUND, the discovery flag will be "false".

Works for me.

Any doubt, im here.

Regards



回答3:

The Discovery issue

Not completely related to your question but a good note nontheless, is that since discovery is a "intensive process" it happens when the scheduler wants it to. If your code is something along the lines of :

startDiscovery();
while(adapter.isDiscovering()){
   // Something Here
}

The code is just going to skip the while block because it hasn't started discovery yet. A quick and certainly dirty fix is to do the following:

startDiscovery();
while(!adapter.isDiscovering());
while(adapter.isDiscovering()){
   // Something Here
}

That is totally nasty and should not work but does. I don't know either.

(Unrelated: Does anybody know why the ACTION_FOUND event never fire?, I looked at my log in adb and using the bluetooth options menu, saw a action.DISCOVERY_STARTED then some time later a action.DISCOVERY_FINISHED, but no FOUND event, only a BluetoothEventManager: DeviceFoundHandler created new CachedBluetoothDevice)



回答4:

Make sure that device is discoverable in settings. You can also do it by firing an intent like this:

Intent discoverableIntent = new Intent(
    BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,0);
startActivity(discoverableIntent);

in onCreate() and then the above code