BroadcastReceiver 中的方法 onReceive 永远不会被调用

苏兰德拉纳斯

我的任务是从我的应用程序打开和关闭蓝牙,然后搜索任何配对的设备。如果找到任何配对的设备,连接到它;否则,发现附近可用的设备并列出它们及其信号强度;每 N 秒更新这些信号强度。当用户选择特定设备时,应建立连接。

package surendra.example.com.mybluetooth;

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.content.SharedPreferences;
import android.hardware.camera2.params.BlackLevelPattern;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    protected static final int DISCOVERY_REQUEST = 1;

    private BluetoothDevice device;

    //Variable for text display
    public TextView statusUpdate;
    public TextView BTHostDetails;
    public TextView BTDevicesAvailable;

    //List of buttons
    public Button turnONBT;
    public Button turnOFFBT;
    public Button scanBTDevices;
    public Button seeRSSI;
    public Button back;

    ArrayAdapter<String> btArrayAdapter;
    //BluetoothAdapter object that initializes the BT hardware on the device
    private BluetoothAdapter mBluetoothAdapter;

    //Broadcast the Bluetooth activities
    BroadcastReceiver bluetoothState = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String prevStateExtra  = BluetoothAdapter.EXTRA_PREVIOUS_STATE;
            String stateExtra = BluetoothAdapter.EXTRA_STATE;

            int state = intent.getIntExtra(stateExtra, -1);
            int previousState = intent.getIntExtra(prevStateExtra, -1);

            String toastText = "";

            switch (state) {
                case(BluetoothAdapter.STATE_TURNING_ON) : {
                    //Already turned ON
                    toastText = "Turning ON Bluetooth";
                    Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                    break;
                }
                case(BluetoothAdapter.STATE_ON): {
                    //Turned ON
                    toastText = "Bluetooth turned ON";
                    Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                    setupUI();
                    break;
                }
                case(BluetoothAdapter.STATE_TURNING_OFF) : {
                    //Already turned OFF
                    toastText = "Turning OFF Bluetooth";
                    Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                    break;
                }
                case(BluetoothAdapter.STATE_OFF) : {
                    //Turned OFF
                    toastText = "Bluetooth turned OFF";
                    Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                    setupUI();
                    break;
                }
            }
        }
    };

    //Represents a remote BT device
    private BluetoothDevice remoteDevice;

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

        //Get default BT adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        setupUI();
    } //end onCreate method

    //Method to setup UI
    private void setupUI() {
        //Get references of each button and text view from the UI
        final TextView statusUpdate = (TextView) findViewById(R.id.statusUpdate);
        final TextView BTHostDetails = (TextView) findViewById(R.id.BTHostDetails);
        final Button turnONBT = (Button) findViewById(R.id.turnONBT);
        final Button turnOFFBT = (Button) findViewById(R.id.turnOFFBT);
        final Button scanBTDevices = (Button) findViewById(R.id.scanBTDevices);
        final Button seeRSSI = (Button) findViewById(R.id.seeRSSI);
        final Button back = (Button) findViewById(R.id.back);

        //Set visibilities of each button
        turnOFFBT.setVisibility(View.GONE);
        seeRSSI.setVisibility(View.GONE);
        back.setVisibility(View.GONE);
        scanBTDevices.setVisibility(View.GONE);
        BTHostDetails.setVisibility(View.GONE);

        //Check if the BT adapter is enabled
        if(mBluetoothAdapter.isEnabled()) {

            //If the BT adapter is enabled, get the name & address of the device
            String devName = mBluetoothAdapter.getName();
            String devAddr = mBluetoothAdapter.getAddress();

            String statusText = devName + " : " + devAddr;
            BTHostDetails.setText(statusText);

            //set the visibilities of the buttons based upon BT status
            BTHostDetails.setVisibility(View.VISIBLE);
            turnONBT.setVisibility(View.GONE);
            turnOFFBT.setVisibility(View.VISIBLE);
            seeRSSI.setVisibility(View.GONE);
            back.setVisibility(View.VISIBLE);
            scanBTDevices.setVisibility(View.VISIBLE);
        } else {
            String tmp = "Bluetooth turned OFF";
            statusUpdate.setText(tmp);
        }

        // We should keep on listening to the TURN ON BLUETOOTH button.
        // When the button turn on bluetooth is clicked, we should proceed to turn Bluetooth ON
        turnONBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //This makes our device discoverable
                String beDiscoverable = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;

                //Intent is the pop up that we see when requesting for permission to use
                //certain interface on the device just like permission for location access etc.
                //Using the intent filter, we can filter the devices whose permissions are changed
                //when the user updates on the intent
                IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

                //This registers a broadcast receiver
                registerReceiver(bluetoothState, filter);

                //If the intent changes from non-discoverable to discoverable, with the filter
                // DISCOVERY_REQUEST, then start the activity.
                startActivityForResult(new Intent(beDiscoverable), DISCOVERY_REQUEST);

                //Change the buttons views
                BTHostDetails.setVisibility(View.VISIBLE);
                turnOFFBT.setVisibility(View.VISIBLE);
                turnONBT.setVisibility(View.INVISIBLE);
                scanBTDevices.setVisibility(View.VISIBLE);
                seeRSSI.setVisibility(View.VISIBLE);
                back.setVisibility(View.INVISIBLE);

                String tmp = "Bluetooth turned ON";
                statusUpdate.setText(tmp);
            }
        });

        //scan devices
        scanBTDevices.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //start discovery of new devices
                mBluetoothAdapter.startDiscovery();

                //see if this device is in a list of paired available devices
                Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                //Toast.makeText(MainActivity.this, "Debug text 0", Toast.LENGTH_SHORT).show();
                if(pairedDevices.size() > 0) {
                    //This means that there are paired devices.
                    // Get the name & address of each device.
                    for(BluetoothDevice device : pairedDevices) {
                        String devName = device.getName();
                        String devAddr = device.getAddress();
                    }

                    List<String> s = new ArrayList<String>();
                    for(BluetoothDevice bt : pairedDevices) {
                        s.add(bt.getName());
                    }
                }
                BroadcastReceiver discoveryResult = new BroadcastReceiver() {

                    @Override
                    public void onReceive(Context context, Intent intent) {
                        String action = intent.getAction();

                        if(BluetoothDevice.ACTION_FOUND.equals(action)) {

                            //BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                            device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                            short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
                            String devName = device.getName();
                            String devAddr = device.getAddress();

                            String tmp = devName + " : " + devAddr + " - " + rssi;
                            statusUpdate.setText(tmp);
                        }
                    }
                };
            }
        });

        //Setup a listener for turning of Bluetooth i.e., for TURN OFF BLUETOOTH button
        turnOFFBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Change the buttons views
                BTHostDetails.setVisibility(View.INVISIBLE);
                turnOFFBT.setVisibility(View.INVISIBLE);
                turnONBT.setVisibility(View.VISIBLE);
                scanBTDevices.setVisibility(View.INVISIBLE);
                seeRSSI.setVisibility(View.INVISIBLE);
                back.setVisibility(View.INVISIBLE);

                String tmp = "Bluetooth turned OFF";
                statusUpdate.setText(tmp);

                mBluetoothAdapter.disable();
            }
        });

        //Back button activity
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setupUI();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == DISCOVERY_REQUEST) {
            String tmp = "Discovery is in progress";
            Toast.makeText(MainActivity.this, tmp , Toast.LENGTH_SHORT).show();
            setupUI();
        }
    }
}

在调试时,我发现 BroadcastReceiver 的 onReceive 方法从未被调用。但是,蓝牙已启用。我错过了什么?

PS:我想把所有的BT活动单独限制在MainActivity中。

共享软件

在调试时,我发现 BroadcastReceiver 的 onReceive 方法从未被调用。但是,蓝牙已启用。

首先,如果启用了蓝牙,并且没有任何改变蓝牙的状态,我不希望收到任何广播。BluetoothAdapter.ACTION_STATE_CHANGED广播被记录发送时,“本地蓝牙适配器的状态已经改变了。” 没有变化意味着没有广播。

其次,您只有在用户点击时才注册bluetoothState为 a 因此,如果在此之前状态发生变化,您将不会收到广播。BroadcastReceiverturnONBT

第三,您注册bluetoothState了错误的操作。您正在为BluetoothDevice.ACTION_FOUND. 该操作用于蓝牙发现,如文档所述改变蓝牙状态的动作是BluetoothAdapter.ACTION_STATE_CHANGEDdiscoveryResult似乎是为了发现,而您似乎从未注册过该接收器。

因为这是我用 Java 或 Android 编写的第一个代码

不会推荐任何涉及蓝牙的东西作为你在 Java 或 Android 中的第一个项目。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

不会调用BroadcastReceiver的onReceive方法

BroadcastReceiver的onReceive方法没有调用吗?

不调用BroadcastReceiver的onReceive

在setAlarm方法期间调用的Alarm BroadcastReceiver的onReceive()被调用

BroadcastReceiver 的 onReceive 方法是否总是在动态注册时调用?

Android AlarmManager,BroadcastReceiver onReceive从未调用

Android BroadcastReceiver:从onReceive方法获取对象

MyApplication 中的方法永远不会被调用

Android BroadcastReceiver onReceive在MainActivity中更新TextView

修改BroadcastReceiver对象的OnReceive()中的图

在Android中的BroadcastReceiver类的onReceive方法中访问ArrayList项

如何使用BroadcastReceiver中的onReceive方法更新TextView

代表方法永远不会被调用

CustomView的“ onDraw()”方法永远不会被调用

Swift Delegate方法永远不会被调用

UITabBarController委托方法永远不会被调用

片段中的onActivityResult永远不会被调用

BroadcastReceiver OnReceive()未触发

使用LocalBroadcastManager注册BroadcastReceiver时未调用onReceive

WALLPAPER_CHANGED的BroadcastReceiver多次调用onReceive():Android

从 StartActivity(ActivityFlags.NewTask) 返回时不调用 BroadcastReceiver OnReceive

使用方法参考定义BroadcastReceiver.onReceive

BroadcastReceiver onReceive方法内的异步任务未运行?

片段中的onClick方法永远不会被调用

BroadcastReceiver.onReceive是否始终在UI线程中运行吗?

永远不会使用AlarmManager调用onReceive()

NSCollectionView的collectionView:itemForRepresentedObjectAtIndexPath:方法永远不会被调用

为什么我的委托方法永远不会被调用?

asp.net中的httphandler永远不会被调用