Android 从未调用BroadcastReceiver中的onReceive方法

Android 从未调用BroadcastReceiver中的onReceive方法,android,bluetooth,android-broadcastreceiver,Android,Bluetooth,Android Broadcastreceiver,我的任务是从我的应用程序打开和关闭蓝牙,然后搜索任何配对设备。如果发现任何配对设备,请连接到该设备;否则,发现附近的可用设备,并列出它们及其信号强度;每N秒更新一次这些信号强度。当用户选择特定设备时,应建立连接 package surendra.example.com.mybluetooth; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.c

我的任务是从我的应用程序打开和关闭蓝牙,然后搜索任何配对设备。如果发现任何配对设备,请连接到该设备;否则,发现附近的可用设备,并列出它们及其信号强度;每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();
        }
    }
}
package surendra.example.com.mybluetooth;
导入android.bluetooth.BluetoothAdapter;
导入android.bluetooth.bluetooth设备;
导入android.content.BroadcastReceiver;
导入android.content.Context;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.content.SharedReferences;
导入android.hardware.camera2.params.BlackLevelPattern;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.view.view;
导入android.widget.ArrayAdapter;
导入android.widget.Button;
导入android.widget.TextView;
导入android.widget.Toast;
导入org.w3c.dom.Text;
导入java.util.ArrayList;
导入java.util.List;
导入java.util.Set;
公共类MainActivity扩展了AppCompatActivity{
受保护的静态最终整数发现请求=1;
私人蓝牙设备;
//用于文本显示的变量
公共文本视图状态更新;
公共文本查看详细信息;
公共文本视图BTDevices可用;
//按钮列表
公共按钮开关;
公共按钮关闭;
公共按钮扫描设备;
公共按钮seeRSSI;
公共按钮返回;
ArrayAdapter btArrayAdapter;
//BluetoothAdapter对象,用于初始化设备上的BT硬件
私人蓝牙适配器mBluetoothAdapter;
//播放蓝牙活动
BroadcastReceiver bluetoothState=新的BroadcastReceiver(){
@凌驾
公共void onReceive(上下文、意图){
字符串prevStateExtra=BluetoothAdapter.EXTRA\u先前的\u状态;
字符串stateExtra=BluetoothAdapter.EXTRA\u状态;
int state=intent.getIntExtra(statextra,-1);
int-previousState=intent.getIntExtra(prevStateExtra,-1);
字符串toastText=“”;
开关(状态){
外壳(蓝牙适配器。状态为打开):{
//已经打开了
toastText=“打开蓝牙”;
Toast.makeText(MainActivity.this、Toast.text、Toast.LENGTH_SHORT).show();
打破
}
外壳(BluetoothAdapter.STATE_ON):{
//打开
toastText=“蓝牙已打开”;
Toast.makeText(MainActivity.this、Toast.text、Toast.LENGTH_SHORT).show();
setupUI();
打破
}
外壳(蓝牙适配器。状态为关闭):{
//已关闭
toast text=“关闭蓝牙”;
Toast.makeText(MainActivity.this、Toast.text、Toast.LENGTH_SHORT).show();
打破
}
外壳(蓝牙适配器。状态为关闭):{
//关掉
toastText=“蓝牙已关闭”;
Toast.makeText(MainActivity.this、Toast.text、Toast.LENGTH_SHORT).show();
setupUI();
打破
}
}
}
};
//表示远程BT设备
专用蓝牙设备远程设备;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取默认BT适配器
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
setupUI();
}//结束onCreate方法
//方法来设置用户界面
私有void setupUI(){
//从UI获取每个按钮和文本视图的引用
最终文本视图状态更新=(文本视图)findViewById(R.id.statusUpdate);
最终文本视图BTHostDetails=(文本视图)findViewById(R.id.BTHostDetails);
最终按钮开启BT=(按钮)findViewById(R.id.turnONBT);
最终按钮关闭BT=(按钮)findViewById(R.id.turnOFFBT);
最终按钮scanBTDevices=(按钮)findViewById(R.id.scanBTDevices);
最终按钮seeRSSI=(按钮)findViewById(R.id.seeRSSI);
最终按钮返回=(按钮)findViewById(R.id.back);
//设置每个按钮的可视性
关闭bt.setVisibility(视图已消失);
seeRSSI.setVisibility(View.GONE);
back.setVisibility(View.GONE);
scanBTDevices.setVisibility(View.GONE);
BTHostDetails.setVisibility(View.GONE);
//检查BT适配器是否已启用
if(mBluetoothAdapter.isEnabled()){
//如果BT适配器已启用,请获取设备的名称和地址
字符串devName=mBluetoothAdapter.getName();
字符串devAddr=mBluetoothAdapter.getAddress();
字符串statusText=devName+“:”+devAddr;
BTHostDetails.setText(statusText);
//根据BT状态设置按钮的可视性
BTHostDetails.setVisibility(View.VISIBLE);
打开bt.setVisibility(视图已消失);
关闭bt.setVisibility(视图可见);
seeRSSI.setVisibility(View.GONE);
back.setVisibility(View.VISIBLE);
scanBTDevices.setVisibility(View.VISIBLE);
}否则{
字符串tmp=“蓝牙已关闭”;
statusUpdate.setText(tmp);
}
//我们应该继续收听打开蓝牙按钮。
//单击“打开蓝牙”按钮后,我们应继续打开蓝牙
turnONBT.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
//这使得