蓝牙:ACTION_FOUND或ACTION_DISCOVERY_FINISHED没有广播

时间:2012-02-24 10:21:12

标签: android bluetooth broadcastreceiver

这个简单的广播接收者永远不会收到任何东西。没有从BluetoothDevice发现设备,也没有从BluetoothAdapter开始/停止发现。

在代码的前面部分,我检查蓝牙是否已启用,BluetoothAdapter是否正确列出了三个配对设备。我尝试过在手机中手动取消配对的变体,我打开和关闭三个远程设备的蓝牙可见性。但我的广播接收器没有记录任何内容。我用布局按钮开始/停止发现。 startDiscovery()始终返回truecancelDiscovery()始终返回false。该代码基本上来自Android蓝牙开发指南。

我的代码:

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

再次编辑: 改为:

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

当我点击其中一个配对的远程设备(耳机)上的物理按钮时,会记录以下内容,但仍未记录任何内容。我想这是其他应用程序或操作系统,它不是我的应用程序:

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

4 个答案:

答案 0 :(得分:2)

您似乎没有在代码中注册广播接收器:

IntentFilter intFilter = new IntentFilter();
intFilter.addAction(BluetoothDevice.ACTION_FOUND);
intFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
你的onResume上的

registerReceiver(intentReceiver , intFilter);
onPause中的

unregisterReceiver(intentReceiver);

答案 1 :(得分:2)

我有同样的问题,按照我的解决方案:

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

在我取消发现之后,如果BroadcastReceiver捕获了BluetoothDevice.ACTION_FOUND,则发现标志将为“false”。

适合我。

有任何疑问,我在这里。

此致

答案 2 :(得分:1)

确保设备中的设备可被发现。您也可以通过触发这样的意图来实现:

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

然后是上面的代码

答案 3 :(得分:1)

发现问题

与你的问题并不完全相关,但是一个好的注意事项是,由于发现是一个“密集的过程”,它会在调度程序需要时发生。如果您的代码类似于:

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

代码只是跳过while块,因为它尚未启动发现。一个快速且肯定是脏的修复方法是执行以下操作:

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

这是完全令人讨厌的,不应该工作,但确实如此。 我也不知道。

(不相关:有人知道为什么ACTION_FOUND事件永远不会发生吗?,我看着我的登录adb并使用蓝牙选项菜单,看到了一个动作.DISCOVERY_STARTED然后一段时间后动作.DISCOVERY_FINISHED,但没有FOUND事件,只有BluetoothEventManager: DeviceFoundHandler created new CachedBluetoothDevice