Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

android - How to detect Bluetooth state change using a broadcast receiver?

I am trying to make an app that shows a toast when the device's Bluetooth turned on. I wanna do that even when my app is not running. So I should use a broadcast receiver, add some permissions, an intent-filter to android manifest and make a java class but I don't know the details.

What should I do? Which permissions should I use?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

AS far as permissions go, to detect the state change of bluetooth you need to add this to your AndroidManifest.xml.

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

An example receiver would look like this, you add this code to where you want to handle the broadcast, for example an activity:

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
            public void onReceive (Context context, Intent intent) {
                String action = intent.getAction();

                if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                    if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) 
    == BluetoothAdapter.STATE_OFF)
    // Bluetooth is disconnected, do handling here
}

}

        };

To use the receiver, you need to register it. Which you can do as follows. I register the receiver in my main activity.

registerReceiver(this, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

You could also decide to add all of it to your AndroidManifest.xml. This way you can make a special class for the receiver and handle it there. No need to register the receiver, just make the class and add the below code to the AndroidManifest

<receiver
        android:name=".packagename.NameOfBroadcastReceiverClass"
        android:enabled="true">
    <intent-filter>
        <action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
    </intent-filter>
</receiver>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...