2016-12-26 59 views
0

我正在为蓝牙客户端开发一个应用程序,并且在这个应用程序中有一个列表视图,列出所有连接的设备。首先,应用程序将检查蓝牙的可用性,然后尝试连接到另一个设备(服务器),除此之外,我初始化清单文件中的意图过滤器。 下面是我的代码:蓝牙:onReceive()和registerReceiver()这些方法从未被调用

public class MainActivity extends AppCompatActivity { 
    ArrayAdapter<String> listAdapter; 
    ListView listView; 
    BluetoothAdapter mBluetoothAdapter; 
    Set<BluetoothDevice> bondedDevices; 
    private BluetoothSocket socket; 
    Intent discoverableIntent; 
    private BluetoothDevice remoteDevice; 
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      if(intent.getAction().equalsIgnoreCase("android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED")) 
      { 
       Log.i("Connect", "Connecting.>>>>"); 
       unregisterReceiver(this); 
       remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       String Temp1 = remoteDevice.getName(); 
       String Temp2 = remoteDevice.getAddress(); 
       listAdapter.add(Temp1 + Temp2); 
       listView.setAdapter(listAdapter); 
       new Thread(reader).start(); 
      } 
     } 
    }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     init(); 
     IntentFilter intentFilter = new IntentFilter("com.example.jackpowell.bluetoothclient.ACTION_ACL_CONNECTED"); 
     registerReceiver(mReceiver,intentFilter); 

     startDiscovery(); 

    } 

    private void startDiscovery() { 
     mBluetoothAdapter.cancelDiscovery(); 
     mBluetoothAdapter.startDiscovery(); 
    } 

    public void init() { 
     listView = (ListView)findViewById(R.id.listView); 
     listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0); 

     mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
     if (mBluetoothAdapter == null) { 
      Toast.makeText(MainActivity.this, "Bluetooth is not supported in this device", Toast.LENGTH_SHORT).show(); 
      finish(); 
     } else { 
      if (!mBluetoothAdapter.isEnabled()) { 
       turnOnBluetooth(); 
      } 
     } 

     bondedDevices = mBluetoothAdapter.getBondedDevices(); 

     discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 
     startActivity(discoverableIntent); 

    } 

    private Runnable reader = new Runnable() { 
     @Override 
     public void run() { 
      try { 
       Log.i("Connect","Connecting..........."); 
       android.util.Log.e("TrackingFlow", "Found: " + remoteDevice.getName()); 
       UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a19-03002011c456"); 
       socket = remoteDevice.createRfcommSocketToServiceRecord(uuid); 
       socket.connect(); 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }; 

    private void turnOnBluetooth() { 
     Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivityForResult(enableBtIntent, 1); 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (resultCode == RESULT_CANCELED) { 
      Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show(); 
      finish(); 
     } 
    } 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     unregisterReceiver(mReceiver); 
    } 



} 

我的清单:现在

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme"> 
    <activity android:name=".MainActivity"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 
<uses-permission android:name="android.permission.BLUETOOTH" /> 
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> 


<receiver android:name="bluetoothclient"> 
    <intent-filter> 
     <action android:name="android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED" /> 
    </intent-filter> 
</receiver> 

问题是的onReceive()和registerReceiver()这些方法不会被调用,或者它已经叫,我只是不明白。如果调用这些方法,日志猫应显示日志命令。为什么这些方法从未被称为?先谢谢你!

+0

你可以在棉花糖上+设备的测试呢? – Harshit

+0

是的。安卓版本6.0.1 – JackPowell

回答

0

动作名称为"android.bluetooth.device.action.ACL_CONNECTED"(用于清单中)或BluetoothDevice.ACTION_ACL_CONNECTED(用于代码中,用于意图过滤器)。代码中的操作名称看起来不对。

注意,要在清单中注册receiver,接收者名称应该是基于BroadcastReceiver的公共类,不知道上面代码中的“bluetoothclient”含义是什么(您没有显示接收者代码)。

通常,您不需要在活动中同时包含明确的接收者和意图过滤器接收者,一个可能就足够了。主要区别在于明细接收者可以独立于活动生命周期并且即使在活动未运行时也能接收。

也试着聆听ACTION_FOUND(在startDiscovery后每documentation您将收到BluetoothDevice.ACTION_FOUND)等,并尝试减少到​​最小范例。您还需要检查startDiscovery()的结果,该结果可能在失败时返回false。

这里稍微从发现设备部分修改样本:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    ... 

    // Register for broadcasts 
    IntentFilter filter = new IntentFilter(); 
    filter.addAction(BluetoothDevice.ACTION_FOUND); 
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); 
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); 
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); 
    registerReceiver(mReceiver, filter); 
    ... 
    if(!mBluetoothAdapter.startDiscovery()){ 
      Log.e("Bluetooth", "discovery error"); 
    } 
} 

// Create a BroadcastReceiver for bluetooth actions 
private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     Log.i("Bluetooth", "got action " + action); 
     if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
      // Discovery has found a device. Get the BluetoothDevice 
      // object and its info from the Intent. 
      BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
      String deviceName = device.getName(); 
      String deviceHardwareAddress = device.getAddress(); // MAC address 
      Log.i("Bluetooth", "got device " + deviceName); 
     } 
    } 
}; 

@Override 
protected void onDestroy() { 
    super.onDestroy(); 
    ... 

    // Don't forget to unregister the ACTION_FOUND receiver. 
    unregisterReceiver(mReceiver); 
} 

还要注意,每本question/answer,在某些设备上如预期的发现并不总是工作,有需要的解决方法。


顺便说一句,你检查logcat的其他错误,例如拒绝权限等?您可以尝试启用位置并添加位置权限。

这里是工作示例显示所有设备:

AndroidManifest.xml中

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.testbluetooth" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="17" 
     android:targetSdkVersion="21" /> 

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


    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name=".MainActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

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

</manifest> 

MainActivity.java

package com.example.testbluetooth; 

import android.app.Activity; 
import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.ViewGroup.LayoutParams; 
import android.widget.FrameLayout; 
import android.widget.TextView; 

public class MainActivity extends Activity { 

    TextView textView; 
    StringBuilder text = new StringBuilder(); 

    private void addLine(String line) 
    { 
     Log.i(getClass().getSimpleName(), line); 
     text.append("[bluetooth] ").append(line).append('\n'); 
     if(textView!=null) 
      textView.setText(text);  
    } 

    BluetoothAdapter mBluetoothAdapter; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     //setContentView(R.layout.activity_main); 
     FrameLayout content = new FrameLayout(this); 
     textView = new TextView(this); 
     content.addView(textView, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); 
     addLine("onCreate"); 
     setContentView(content); 

     // Register for broadcasts 
     IntentFilter filter = new IntentFilter(); 
     filter.addAction(BluetoothDevice.ACTION_FOUND); 
     filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); 
     filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); 
     filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); 
     registerReceiver(mReceiver, filter); 

     mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 

     for(BluetoothDevice pairedDevice : mBluetoothAdapter.getBondedDevices()) 
     { 
      addLine("got paired device " + pairedDevice.getName()); 
     } 

     if(!mBluetoothAdapter.startDiscovery()){ 
      addLine("ERROR: discovery error"); 
     } 
     else 
     { 
      addLine("starting discovery");   
     } 

    } 

// Create a BroadcastReceiver for bluetooth actions 
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      addLine("got action " + action); 
      if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
       // Discovery has found a device. Get the BluetoothDevice 
       // object and its info from the Intent. 
       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       String deviceName = device.getName(); 
       //String deviceHardwareAddress = device.getAddress(); // MAC address 
       addLine("got device " + deviceName); 
      } 
     } 
    };  
} 
+0

嗨,谢谢你的回复! “bluetoothclient”我修改为com.example.jackpowell.bluetoothclient。而且我也完成了你对此的评论。结果仍然相同。 – JackPowell

+0

很难说没有看到你的修改过的代码,你是否尝试注释掉所有'if('in receiver并放入只是登录行?你是否真的在运行期间连接/断开蓝牙设备? –

+0

我扩大了答案,看看是否有帮助 –