Android BroadCastReceiver 未被调用进行蓝牙聊天
Android BroadCastReceiver Not Getting Called for Bluetooth Chat
我正在尝试在蓝牙发现完成后获取设备元数据,以开始文本数据传输。我使用广播接收器来获取发现的设备。
这是我的 activity 代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
private Button btnListen, btnSearch, btnStop;
private TextInputLayout til_incoming, til_outgoing;
private TextInputEditText incomingTET, outgoingTET;
private ListView devicesListView;
private BluetoothAdapter mBTAdapter;
private BluetoothSocket mSocket;
private ArrayAdapter<BluetoothDevice> adapter;
private ArrayList<BluetoothDevice> mBTDeviceList = new ArrayList<>();
private UUID uuid = UUID.fromString("c18fdef0-9c59-11e2-9e96-0800200c9a66");
private static final int REQUEST_ENABLE_BT = 1;
private static final int REQUEST_DISCOVERY = 2;
private static final int DISCOVERY_TIME_OUT = 3 * 1000 * 60;
private IntentFilter filter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
adapter = new ArrayAdapter<BluetoothDevice>(this, android.R.layout.simple_list_item_1, mBTDeviceList);
devicesListView.setAdapter(adapter);
setEnableUI(false);
mBTAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBTAdapter == null) {
Snackbar.make(findViewById(android.R.id.content), "Your Device Has no Bluetooth Adapter", Snackbar.LENGTH_LONG).show();
finish();
} else {
if (!mBTAdapter.isEnabled()){
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
}
if (mBTAdapter.isEnabled()){
setUpListeners();
setEnableUI(true);
}
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
}
private void setUpListeners() {
btnListen.setOnClickListener(this);
btnSearch.setOnClickListener(this);
btnStop.setOnClickListener(this);
devicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
}
});
}
private void setEnableUI(boolean b) {
btnListen.setEnabled(b);
btnSearch.setEnabled(b);
btnStop.setEnabled(b);
devicesListView.setVisibility(View.GONE);
}
private void init() {
btnListen = findViewById(R.id.btnListen);
btnSearch = findViewById(R.id.btnSearch);
btnStop = findViewById(R.id.btnStop);
incomingTET = findViewById(R.id.incomingTET);
outgoingTET = findViewById(R.id.outgoingTET);
til_incoming = findViewById(R.id.til_incoming);
til_outgoing = findViewById(R.id.til_outgoing);
devicesListView = findViewById(R.id.devicesListView);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnListen:
Log.d(TAG, "Listening for Devices");
Intent discoverIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERY_TIME_OUT);
startActivityForResult(discoverIntent, REQUEST_DISCOVERY);
break;
case R.id.btnSearch:
Log.d(TAG, "Searching for Devices");
discoverBluetoothDevices();
registerBluetoothReceiver();
break;
case R.id.btnStop:
if (mBTAdapter.isEnabled()){
mBTAdapter.disable();
Log.d(TAG, "Stopped Listening for Devices");
Snackbar.make(findViewById(android.R.id.content), "Bluetooth Switched Off", Snackbar.LENGTH_LONG).show();
}
break;
}
}
private void discoverBluetoothDevices() {
boolean discoveredStatus = mBTAdapter.startDiscovery();
if (discoveredStatus == false){
Snackbar.make(findViewById(android.R.id.content), "Bluetooth Discovery Failed...\t Try Again", Snackbar.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Discovering Nearby Devices", Toast.LENGTH_SHORT).show();
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "OnReceive BR");
if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTDeviceList.add(device);
Log.d(TAG, "Device Name:\t" + device.getName());
Log.d(TAG, "Device Addr:\t" + device.getAddress());
Log.d(TAG, "Device Bond State:\t" + device.getBondState());
Log.d(TAG, "List Size:\t" + mBTDeviceList.size());
adapter.notifyDataSetChanged();
}
}
};
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case REQUEST_ENABLE_BT:
if (resultCode == RESULT_OK){
setEnableUI(true);
}
break;
case REQUEST_DISCOVERY:
if (resultCode == REQUEST_DISCOVERY){
Log.d(TAG, "Visible for:\t" + DISCOVERY_TIME_OUT + "\tseconds");
try {
BluetoothServerSocket serverSocket = mBTAdapter
.listenUsingInsecureRfcommWithServiceRecord("ETEC304 lab8", uuid);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
private void registerBluetoothReceiver() {
this.registerReceiver(mReceiver, filter);
}
@Override
protected void onResume() {
super.onResume();
registerBluetoothReceiver();
}
private void unRegisterBluetoothReceiver() {
this.unregisterReceiver(mReceiver);
}
@Override
protected void onPause() {
super.onPause();
//this.unregisterReceiver(mReceiver);
unRegisterBluetoothReceiver();
}
}
到目前为止,我的解决方案的其他部分都可以工作,除了从不触发的广播接收器。我想知道是否有解决此问题的方法以及如何避免将来发生这种情况。
清单文件:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
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>
在您的 AndroidMenifest.xml
文件中添加此权限。
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
你应该先调用 registerBluetoothReceiver()
然后再调用 discoverBluetoothDevices()
;
case R.id.btnSearch:
Log.d(TAG, "Searching for Devices");
registerBluetoothReceiver();
discoverBluetoothDevices();
我正在尝试在蓝牙发现完成后获取设备元数据,以开始文本数据传输。我使用广播接收器来获取发现的设备。
这是我的 activity 代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
private Button btnListen, btnSearch, btnStop;
private TextInputLayout til_incoming, til_outgoing;
private TextInputEditText incomingTET, outgoingTET;
private ListView devicesListView;
private BluetoothAdapter mBTAdapter;
private BluetoothSocket mSocket;
private ArrayAdapter<BluetoothDevice> adapter;
private ArrayList<BluetoothDevice> mBTDeviceList = new ArrayList<>();
private UUID uuid = UUID.fromString("c18fdef0-9c59-11e2-9e96-0800200c9a66");
private static final int REQUEST_ENABLE_BT = 1;
private static final int REQUEST_DISCOVERY = 2;
private static final int DISCOVERY_TIME_OUT = 3 * 1000 * 60;
private IntentFilter filter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
adapter = new ArrayAdapter<BluetoothDevice>(this, android.R.layout.simple_list_item_1, mBTDeviceList);
devicesListView.setAdapter(adapter);
setEnableUI(false);
mBTAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBTAdapter == null) {
Snackbar.make(findViewById(android.R.id.content), "Your Device Has no Bluetooth Adapter", Snackbar.LENGTH_LONG).show();
finish();
} else {
if (!mBTAdapter.isEnabled()){
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
}
if (mBTAdapter.isEnabled()){
setUpListeners();
setEnableUI(true);
}
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
}
private void setUpListeners() {
btnListen.setOnClickListener(this);
btnSearch.setOnClickListener(this);
btnStop.setOnClickListener(this);
devicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
}
});
}
private void setEnableUI(boolean b) {
btnListen.setEnabled(b);
btnSearch.setEnabled(b);
btnStop.setEnabled(b);
devicesListView.setVisibility(View.GONE);
}
private void init() {
btnListen = findViewById(R.id.btnListen);
btnSearch = findViewById(R.id.btnSearch);
btnStop = findViewById(R.id.btnStop);
incomingTET = findViewById(R.id.incomingTET);
outgoingTET = findViewById(R.id.outgoingTET);
til_incoming = findViewById(R.id.til_incoming);
til_outgoing = findViewById(R.id.til_outgoing);
devicesListView = findViewById(R.id.devicesListView);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnListen:
Log.d(TAG, "Listening for Devices");
Intent discoverIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERY_TIME_OUT);
startActivityForResult(discoverIntent, REQUEST_DISCOVERY);
break;
case R.id.btnSearch:
Log.d(TAG, "Searching for Devices");
discoverBluetoothDevices();
registerBluetoothReceiver();
break;
case R.id.btnStop:
if (mBTAdapter.isEnabled()){
mBTAdapter.disable();
Log.d(TAG, "Stopped Listening for Devices");
Snackbar.make(findViewById(android.R.id.content), "Bluetooth Switched Off", Snackbar.LENGTH_LONG).show();
}
break;
}
}
private void discoverBluetoothDevices() {
boolean discoveredStatus = mBTAdapter.startDiscovery();
if (discoveredStatus == false){
Snackbar.make(findViewById(android.R.id.content), "Bluetooth Discovery Failed...\t Try Again", Snackbar.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Discovering Nearby Devices", Toast.LENGTH_SHORT).show();
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "OnReceive BR");
if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTDeviceList.add(device);
Log.d(TAG, "Device Name:\t" + device.getName());
Log.d(TAG, "Device Addr:\t" + device.getAddress());
Log.d(TAG, "Device Bond State:\t" + device.getBondState());
Log.d(TAG, "List Size:\t" + mBTDeviceList.size());
adapter.notifyDataSetChanged();
}
}
};
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case REQUEST_ENABLE_BT:
if (resultCode == RESULT_OK){
setEnableUI(true);
}
break;
case REQUEST_DISCOVERY:
if (resultCode == REQUEST_DISCOVERY){
Log.d(TAG, "Visible for:\t" + DISCOVERY_TIME_OUT + "\tseconds");
try {
BluetoothServerSocket serverSocket = mBTAdapter
.listenUsingInsecureRfcommWithServiceRecord("ETEC304 lab8", uuid);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
private void registerBluetoothReceiver() {
this.registerReceiver(mReceiver, filter);
}
@Override
protected void onResume() {
super.onResume();
registerBluetoothReceiver();
}
private void unRegisterBluetoothReceiver() {
this.unregisterReceiver(mReceiver);
}
@Override
protected void onPause() {
super.onPause();
//this.unregisterReceiver(mReceiver);
unRegisterBluetoothReceiver();
}
}
到目前为止,我的解决方案的其他部分都可以工作,除了从不触发的广播接收器。我想知道是否有解决此问题的方法以及如何避免将来发生这种情况。
清单文件:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
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>
在您的 AndroidMenifest.xml
文件中添加此权限。
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
你应该先调用 registerBluetoothReceiver()
然后再调用 discoverBluetoothDevices()
;
case R.id.btnSearch:
Log.d(TAG, "Searching for Devices");
registerBluetoothReceiver();
discoverBluetoothDevices();