Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android-BluetoothAdapter

android-BluetoothAdapter

編輯:關於Android編程

Represents the local device Bluetooth adapter. TheBluetoothAdapterlets you perform fundamental Bluetooth tasks, such as initiate device discovery, query a list of bonded (paired) devices, instantiate aBluetoothDeviceusing a known MAC address, and create aBluetoothServerSocketto listen for connection requests from other devices, and start a scan for Bluetooth LE devices.

To get aBluetoothAdapterrepresenting the local Bluetooth adapter, when running on JELLY_BEAN_MR1 and below, call the staticgetDefaultAdapter()method; when running on JELLY_BEAN_MR2 and higher, callgetAdapter(). Fundamentally, this is your starting point for all Bluetooth actions. Once you have the local adapter, you can get a set ofBluetoothDeviceobjects representing all paired devices withgetBondedDevices(); start device discovery withstartDiscovery(); or create aBluetoothServerSocketto listen for incoming connection requests withlistenUsingRfcommWithServiceRecord(String, UUID); or start a scan for Bluetooth LE devices withstartLeScan(LeScanCallback).

This class is thread safe.

Note:Most methods require theBLUETOOTHpermission and some also require theBLUETOOTH_ADMINpermission.

Developer Guides

For more information about using Bluetooth, read theBluetoothdeveloper guide.

See also:

  • BluetoothDevice
  • BluetoothServerSocket

Summary


Nested classes

interface BluetoothAdapter.LeScanCallback

Callback interface used to deliver LE scan results.

Constants

String ACTION_CONNECTION_STATE_CHANGED

Intent used to broadcast the change in connection state of the local Bluetooth adapter to a profile of the remote device.

String ACTION_DISCOVERY_FINISHED

Broadcast Action: The local Bluetooth adapter has finished the device discovery process.

String ACTION_DISCOVERY_STARTED

Broadcast Action: The local Bluetooth adapter has started the remote device discovery process.

String ACTION_LOCAL_NAME_CHANGED

Broadcast Action: The local Bluetooth adapter has changed its friendly Bluetooth name.

String ACTION_REQUEST_DISCOVERABLE

Activity Action: Show a system activity that requests discoverable mode.

String ACTION_REQUEST_ENABLE

Activity Action: Show a system activity that allows the user to turn on Bluetooth.

String ACTION_SCAN_MODE_CHANGED

Broadcast Action: Indicates the Bluetooth scan mode of the local Adapter has changed.

String ACTION_STATE_CHANGED

Broadcast Action: The state of the local Bluetooth adapter has been changed.

int ERROR

Sentinel error value for this class.

String EXTRA_CONNECTION_STATE

Extra used byACTION_CONNECTION_STATE_CHANGEDThis extra represents the current connection state.

String EXTRA_DISCOVERABLE_DURATION

Used as an optional int extra field inACTION_REQUEST_DISCOVERABLEintents to request a specific duration for discoverability in seconds.

String EXTRA_LOCAL_NAME

Used as a String extra field inACTION_LOCAL_NAME_CHANGEDintents to request the local Bluetooth name.

String EXTRA_PREVIOUS_CONNECTION_STATE

Extra used byACTION_CONNECTION_STATE_CHANGEDThis extra represents the previous connection state.

String EXTRA_PREVIOUS_SCAN_MODE

Used as an int extra field inACTION_SCAN_MODE_CHANGEDintents to request the previous scan mode.

String EXTRA_PREVIOUS_STATE

Used as an int extra field inACTION_STATE_CHANGEDintents to request the previous power state.

String EXTRA_SCAN_MODE

Used as an int extra field inACTION_SCAN_MODE_CHANGEDintents to request the current scan mode.

String EXTRA_STATE

Used as an int extra field inACTION_STATE_CHANGEDintents to request the current power state.

int SCAN_MODE_CONNECTABLE

Indicates that inquiry scan is disabled, but page scan is enabled on the local Bluetooth adapter.

int SCAN_MODE_CONNECTABLE_DISCOVERABLE

Indicates that both inquiry scan and page scan are enabled on the local Bluetooth adapter.

int SCAN_MODE_NONE

Indicates that both inquiry scan and page scan are disabled on the local Bluetooth adapter.

int STATE_CONNECTED

The profile is in connected state

int STATE_CONNECTING

The profile is in connecting state

int STATE_DISCONNECTED

The profile is in disconnected state

int STATE_DISCONNECTING

The profile is in disconnecting state

int STATE_OFF

Indicates the local Bluetooth adapter is off.

int STATE_ON

Indicates the local Bluetooth adapter is on, and ready for use.

int STATE_TURNING_OFF

Indicates the local Bluetooth adapter is turning off.

int STATE_TURNING_ON

Indicates the local Bluetooth adapter is turning on.

Public methods

boolean cancelDiscovery()

Cancel the current device discovery process.

static boolean checkBluetoothAddress(Stringaddress)

Validate a String Bluetooth address, such as "00:43:A8:23:10:F0"

Alphabetic characters must be uppercase to be valid.

void closeProfileProxy(int profile,BluetoothProfileproxy)

Close the connection of the profile proxy to the Service.

boolean disable()

Turn off the local Bluetooth adapter—do not use without explicit user action to turn off Bluetooth.

boolean enable()

Turn on the local Bluetooth adapter—do not use without explicit user action to turn on Bluetooth.

String getAddress()

Returns the hardware address of the local Bluetooth adapter.

BluetoothLeAdvertiser getBluetoothLeAdvertiser()

Returns aBluetoothLeAdvertiserobject for Bluetooth LE Advertising operations.

BluetoothLeScanner getBluetoothLeScanner()

Returns aBluetoothLeScannerobject for Bluetooth LE scan operations.

Set<BluetoothDevice> getBondedDevices()

Return the set ofBluetoothDeviceobjects that are bonded (paired) to the local adapter.

staticBluetoothAdapter getDefaultAdapter()

Get a handle to the default local Bluetooth adapter.

String getName()

Get the friendly Bluetooth name of the local Bluetooth adapter.

int getProfileConnectionState(int profile)

Get the current connection state of a profile.

boolean getProfileProxy(Contextcontext,BluetoothProfile.ServiceListenerlistener, int profile)

Get the profile proxy object associated with the profile.

BluetoothDevice getRemoteDevice(byte[] address)

Get aBluetoothDeviceobject for the given Bluetooth hardware address.

BluetoothDevice getRemoteDevice(Stringaddress)

Get aBluetoothDeviceobject for the given Bluetooth hardware address.

int getScanMode()

Get the current Bluetooth scan mode of the local Bluetooth adapter.

int getState()

Get the current state of the local Bluetooth adapter.

boolean isDiscovering()

Return true if the local Bluetooth adapter is currently in the device discovery process.

boolean isEnabled()

Return true if Bluetooth is currently enabled and ready for use.

boolean isMultipleAdvertisementSupported()

Return true if the multi advertisement is supported by the chipset

boolean isOffloadedFilteringSupported()

Return true if offloaded filters are supported

boolean isOffloadedScanBatchingSupported()

Return true if offloaded scan batching is supported

BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord(Stringname,UUIDuuid)

Create a listening, insecure RFCOMM Bluetooth socket with Service Record.

BluetoothServerSocket listenUsingRfcommWithServiceRecord(Stringname,UUIDuuid)

Create a listening, secure RFCOMM Bluetooth socket with Service Record.

boolean setName(Stringname)

Set the friendly Bluetooth name of the local Bluetooth adapter.

boolean startDiscovery()

Start the remote device discovery process.

boolean startLeScan(UUID[]serviceUuids,BluetoothAdapter.LeScanCallbackcallback)

This method was deprecated in API level 21. usestartScan(List, ScanSettings, ScanCallback)instead.

boolean startLeScan(BluetoothAdapter.LeScanCallbackcallback)

This method was deprecated in API level 21. usestartScan(List, ScanSettings, ScanCallback)instead.

void stopLeScan(BluetoothAdapter.LeScanCallbackcallback)

This method was deprecated in API level 21. UsestopScan(ScanCallback)instead.

Protected methods

void finalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Inherited methods

\From classjava.lang.Object  

Constants


ACTION_CONNECTION_STATE_CHANGED

Added inAPI level 11
String ACTION_CONNECTION_STATE_CHANGED

Intent used to broadcast the change in connection state of the local Bluetooth adapter to a profile of the remote device. When the adapter is not connected to any profiles of any remote devices and it attempts a connection to a profile this intent will sent. Once connected, this intent will not be sent for any more connection attempts to any profiles of any remote device. When the adapter disconnects from the last profile its connected to of any remote device, this intent will be sent.

This intent is useful for applications that are only concerned about whether the local adapter is connected to any profile of any device and are not really concerned about which profile. For example, an application which displays an icon to display whether Bluetooth is connected or not can use this intent.

This intent will have 3 extras:EXTRA_CONNECTION_STATE- The current connection state.EXTRA_PREVIOUS_CONNECTION_STATE- The previous connection state.EXTRA_DEVICE- The remote device.EXTRA_CONNECTION_STATEorEXTRA_PREVIOUS_CONNECTION_STATEcan be any ofSTATE_DISCONNECTED,STATE_CONNECTING,STATE_CONNECTED,STATE_DISCONNECTING.

RequiresBLUETOOTHto receive.

Constant Value: "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED"

ACTION_DISCOVERY_FINISHED

Added inAPI level 5
String ACTION_DISCOVERY_FINISHED

Broadcast Action: The local Bluetooth adapter has finished the device discovery process.

RequiresBLUETOOTHto receive.

Constant Value: "android.bluetooth.adapter.action.DISCOVERY_FINISHED"

ACTION_DISCOVERY_STARTED

Added inAPI level 5
String ACTION_DISCOVERY_STARTED

Broadcast Action: The local Bluetooth adapter has started the remote device discovery process.

This usually involves an inquiry scan of about 12 seconds, followed by a page scan of each new device to retrieve its Bluetooth name.

Register forACTION_FOUNDto be notified as remote Bluetooth devices are found.

Device discovery is a heavyweight procedure. New connections to remote Bluetooth devices should not be attempted while discovery is in progress, and existing connections will experience limited bandwidth and high latency. UsecancelDiscovery()to cancel an ongoing discovery.

RequiresBLUETOOTHto receive.

Constant Value: "android.bluetooth.adapter.action.DISCOVERY_STARTED"

ACTION_LOCAL_NAME_CHANGED

Added inAPI level 5
String ACTION_LOCAL_NAME_CHANGED

Broadcast Action: The local Bluetooth adapter has changed its friendly Bluetooth name.

This name is visible to remote Bluetooth devices.

Always contains the extra fieldEXTRA_LOCAL_NAMEcontaining the name.

RequiresBLUETOOTHto receive.

Constant Value: "android.bluetooth.adapter.action.LOCAL_NAME_CHANGED"

ACTION_REQUEST_DISCOVERABLE

Added inAPI level 5
String ACTION_REQUEST_DISCOVERABLE

Activity Action: Show a system activity that requests discoverable mode. This activity will also request the user to turn on Bluetooth if it is not currently enabled.

Discoverable mode is equivalent toSCAN_MODE_CONNECTABLE_DISCOVERABLE. It allows remote devices to see this Bluetooth adapter when they perform a discovery.

For privacy, Android is not discoverable by default.

The sender of this Intent can optionally use extra fieldEXTRA_DISCOVERABLE_DURATIONto request the duration of discoverability. Currently the default duration is 120 seconds, and maximum duration is capped at 300 seconds for each request.

Notification of the result of this activity is posted using theonActivityResult(int, int, Intent)callback. TheresultCodewill be the duration (in seconds) of discoverability orRESULT_CANCELEDif the user rejected discoverability or an error has occurred.

Applications can also listen forACTION_SCAN_MODE_CHANGEDfor global notification whenever the scan mode changes. For example, an application can be notified when the device has ended discoverability.

RequiresBLUETOOTH

Constant Value: "android.bluetooth.adapter.action.REQUEST_DISCOVERABLE"

ACTION_REQUEST_ENABLE

Added inAPI level 5
String ACTION_REQUEST_ENABLE

Activity Action: Show a system activity that allows the user to turn on Bluetooth.

This system activity will return once Bluetooth has completed turning on, or the user has decided not to turn Bluetooth on.

Notification of the result of this activity is posted using theonActivityResult(int, int, Intent)callback. TheresultCodewill beRESULT_OKif Bluetooth has been turned on orRESULT_CANCELEDif the user has rejected the request or an error has occurred.

Applications can also listen forACTION_STATE_CHANGEDfor global notification whenever Bluetooth is turned on or off.

RequiresBLUETOOTH

Constant Value: "android.bluetooth.adapter.action.REQUEST_ENABLE"

ACTION_SCAN_MODE_CHANGED

Added inAPI level 5
String ACTION_SCAN_MODE_CHANGED

Broadcast Action: Indicates the Bluetooth scan mode of the local Adapter has changed.

Always contains the extra fieldsEXTRA_SCAN_MODEandEXTRA_PREVIOUS_SCAN_MODEcontaining the new and old scan modes respectively.

RequiresBLUETOOTH

Constant Value: "android.bluetooth.adapter.action.SCAN_MODE_CHANGED"

ACTION_STATE_CHANGED

Added inAPI level 5
String ACTION_STATE_CHANGED

Broadcast Action: The state of the local Bluetooth adapter has been changed.

For example, Bluetooth has been turned on or off.

Always contains the extra fieldsEXTRA_STATEandEXTRA_PREVIOUS_STATEcontaining the new and old states respectively.

RequiresBLUETOOTHto receive.

Constant Value: "android.bluetooth.adapter.action.STATE_CHANGED"

ERROR

Added inAPI level 5
int ERROR

Sentinel error value for this class. Guaranteed to not equal any other integer constant in this class. Provided as a convenience for functions that require a sentinel error value, for example:

Intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)

Constant Value: -2147483648 (0x80000000)

EXTRA_CONNECTION_STATE

Added inAPI level 11
String EXTRA_CONNECTION_STATE

Extra used byACTION_CONNECTION_STATE_CHANGEDThis extra represents the current connection state.

Constant Value: "android.bluetooth.adapter.extra.CONNECTION_STATE"

EXTRA_DISCOVERABLE_DURATION

Added inAPI level 5
String EXTRA_DISCOVERABLE_DURATION

Used as an optional int extra field inACTION_REQUEST_DISCOVERABLEintents to request a specific duration for discoverability in seconds. The current default is 120 seconds, and requests over 300 seconds will be capped. These values could change.

Constant Value: "android.bluetooth.adapter.extra.DISCOVERABLE_DURATION"

EXTRA_LOCAL_NAME

Added inAPI level 5
String EXTRA_LOCAL_NAME

Used as a String extra field inACTION_LOCAL_NAME_CHANGEDintents to request the local Bluetooth name.

Constant Value: "android.bluetooth.adapter.extra.LOCAL_NAME"

EXTRA_PREVIOUS_CONNECTION_STATE

Added inAPI level 11
String EXTRA_PREVIOUS_CONNECTION_STATE

Extra used byACTION_CONNECTION_STATE_CHANGEDThis extra represents the previous connection state.

Constant Value: "android.bluetooth.adapter.extra.PREVIOUS_CONNECTION_STATE"

EXTRA_PREVIOUS_SCAN_MODE

Added inAPI level 5
String EXTRA_PREVIOUS_SCAN_MODE

Used as an int extra field inACTION_SCAN_MODE_CHANGEDintents to request the previous scan mode. Possible values are:SCAN_MODE_NONE,SCAN_MODE_CONNECTABLE,SCAN_MODE_CONNECTABLE_DISCOVERABLE,

Constant Value: "android.bluetooth.adapter.extra.PREVIOUS_SCAN_MODE"

EXTRA_PREVIOUS_STATE

Added inAPI level 5
String EXTRA_PREVIOUS_STATE

Used as an int extra field inACTION_STATE_CHANGEDintents to request the previous power state. Possible values are:STATE_OFF,STATE_TURNING_ON,STATE_ON,STATE_TURNING_OFF

Constant Value: "android.bluetooth.adapter.extra.PREVIOUS_STATE"

EXTRA_SCAN_MODE

Added inAPI level 5
String EXTRA_SCAN_MODE

Used as an int extra field inACTION_SCAN_MODE_CHANGEDintents to request the current scan mode. Possible values are:SCAN_MODE_NONE,SCAN_MODE_CONNECTABLE,SCAN_MODE_CONNECTABLE_DISCOVERABLE,

Constant Value: "android.bluetooth.adapter.extra.SCAN_MODE"

EXTRA_STATE

Added inAPI level 5
String EXTRA_STATE

Used as an int extra field inACTION_STATE_CHANGEDintents to request the current power state. Possible values are:STATE_OFF,STATE_TURNING_ON,STATE_ON,STATE_TURNING_OFF,

Constant Value: "android.bluetooth.adapter.extra.STATE"

SCAN_MODE_CONNECTABLE

Added inAPI level 5
int SCAN_MODE_CONNECTABLE

Indicates that inquiry scan is disabled, but page scan is enabled on the local Bluetooth adapter. Therefore this device is not discoverable from remote Bluetooth devices, but is connectable from remote devices that have previously discovered this device.

Constant Value: 21 (0x00000015)

SCAN_MODE_CONNECTABLE_DISCOVERABLE

Added inAPI level 5
int SCAN_MODE_CONNECTABLE_DISCOVERABLE

Indicates that both inquiry scan and page scan are enabled on the local Bluetooth adapter. Therefore this device is both discoverable and connectable from remote Bluetooth devices.

Constant Value: 23 (0x00000017)

SCAN_MODE_NONE

Added inAPI level 5
int SCAN_MODE_NONE

Indicates that both inquiry scan and page scan are disabled on the local Bluetooth adapter. Therefore this device is neither discoverable nor connectable from remote Bluetooth devices.

Constant Value: 20 (0x00000014)

STATE_CONNECTED

Added inAPI level 11
int STATE_CONNECTED

The profile is in connected state

Constant Value: 2 (0x00000002)

STATE_CONNECTING

Added inAPI level 11
int STATE_CONNECTING

The profile is in connecting state

Constant Value: 1 (0x00000001)

STATE_DISCONNECTED

Added inAPI level 11
int STATE_DISCONNECTED

The profile is in disconnected state

Constant Value: 0 (0x00000000)

STATE_DISCONNECTING

Added inAPI level 11
int STATE_DISCONNECTING

The profile is in disconnecting state

Constant Value: 3 (0x00000003)

STATE_OFF

Added inAPI level 5
int STATE_OFF

Indicates the local Bluetooth adapter is off.

Constant Value: 10 (0x0000000a)

STATE_ON

Added inAPI level 5
int STATE_ON

Indicates the local Bluetooth adapter is on, and ready for use.

Constant Value: 12 (0x0000000c)

STATE_TURNING_OFF

Added inAPI level 5
int STATE_TURNING_OFF

Indicates the local Bluetooth adapter is turning off. Local clients should immediately attempt graceful disconnection of any remote links.

Constant Value: 13 (0x0000000d)

STATE_TURNING_ON

Added inAPI level 5
int STATE_TURNING_ON

Indicates the local Bluetooth adapter is turning on. However local clients should wait forSTATE_ONbefore attempting to use the adapter.

Constant Value: 11 (0x0000000b)

Public methods


cancelDiscovery

Added inAPI level 5
boolean cancelDiscovery ()

Cancel the current device discovery process.

RequiresBLUETOOTH_ADMIN.

Because discovery is a heavyweight procedure for the Bluetooth adapter, this method should always be called before attempting to connect to a remote device withconnect(). Discovery is not managed by the Activity, but is run as a system service, so an application should always call cancel discovery even if it did not directly request a discovery, just to be sure.

If Bluetooth state is notSTATE_ON, this API will return false. After turning on Bluetooth, wait forACTION_STATE_CHANGEDwithSTATE_ONto get the updated value.

Returns boolean true on success, false on error

checkBluetoothAddress

Added inAPI level 5
boolean checkBluetoothAddress (String address)

Validate a String Bluetooth address, such as "00:43:A8:23:10:F0"

Alphabetic characters must be uppercase to be valid.

Parameters address String: Bluetooth address as string Returns boolean true if the address is valid, false otherwise

closeProfileProxy

Added inAPI level 11
void closeProfileProxy (int profile, 
                BluetoothProfile proxy)

Close the connection of the profile proxy to the Service.

Clients should call this when they are no longer using the proxy obtained fromgetProfileProxy(Context, BluetoothProfile.ServiceListener, int). Profile can be one ofHEALTH,HEADSETorA2DP

Parameters proxy BluetoothProfile: Profile proxy object

disable

Added inAPI level 5
boolean disable ()

Turn off the local Bluetooth adapter—do not use without explicit user action to turn off Bluetooth.

This gracefully shuts down all Bluetooth connections, stops Bluetooth system services, and powers down the underlying Bluetooth hardware.

Bluetooth should never be disabled without direct user consent. Thedisable()method is provided only for applications that include a user interface for changing system settings, such as a "power manager" app.

This is an asynchronous call: it will return immediately, and clients should listen forACTION_STATE_CHANGEDto be notified of subsequent adapter state changes. If this call returns true, then the adapter state will immediately transition fromSTATE_ONtoSTATE_TURNING_OFF, and some time later transition to eitherSTATE_OFForSTATE_ON. If this call returns false then there was an immediate problem that will prevent the adapter from being turned off - such as the adapter already being turned off.

Requires theBLUETOOTH_ADMINpermission

Returns boolean true to indicate adapter shutdown has begun, or false on immediate error

enable

Added inAPI level 5
boolean enable ()

Turn on the local Bluetooth adapter—do not use without explicit user action to turn on Bluetooth.

This powers on the underlying Bluetooth hardware, and starts all Bluetooth system services.

Bluetooth should never be enabled without direct user consent. If you want to turn on Bluetooth in order to create a wireless connection, you should use theACTION_REQUEST_ENABLEIntent, which will raise a dialog that requests user permission to turn on Bluetooth. Theenable()method is provided only for applications that include a user interface for changing system settings, such as a "power manager" app.

This is an asynchronous call: it will return immediately, and clients should listen forACTION_STATE_CHANGEDto be notified of subsequent adapter state changes. If this call returns true, then the adapter state will immediately transition fromSTATE_OFFtoSTATE_TURNING_ON, and some time later transition to eitherSTATE_OFForSTATE_ON. If this call returns false then there was an immediate problem that will prevent the adapter from being turned on - such as Airplane mode, or the adapter is already turned on.

Requires theBLUETOOTH_ADMINpermission

Returns boolean true to indicate adapter startup has begun, or false on immediate error

getAddress

Added inAPI level 5
String getAddress ()

Returns the hardware address of the local Bluetooth adapter.

For example, "00:11:22:AA:BB:CC".

RequiresBLUETOOTH

Returns String Bluetooth hardware address as string

getBluetoothLeAdvertiser

Added inAPI level 21
BluetoothLeAdvertiser getBluetoothLeAdvertiser ()

Returns aBluetoothLeAdvertiserobject for Bluetooth LE Advertising operations. Will return null if Bluetooth is turned off or if Bluetooth LE Advertising is not supported on this device.

UseisMultipleAdvertisementSupported()to check whether LE Advertising is supported on this device before calling this method.

Returns BluetoothLeAdvertiser  

getBluetoothLeScanner

Added inAPI level 21
BluetoothLeScanner getBluetoothLeScanner ()

Returns aBluetoothLeScannerobject for Bluetooth LE scan operations.

Returns BluetoothLeScanner  

getBondedDevices

Added inAPI level 5
Set<BluetoothDevice> getBondedDevices ()

Return the set ofBluetoothDeviceobjects that are bonded (paired) to the local adapter.

If Bluetooth state is notSTATE_ON, this API will return an empty set. After turning on Bluetooth, wait forACTION_STATE_CHANGEDwithSTATE_ONto get the updated value.

RequiresBLUETOOTH.

Returns Set<BluetoothDevice> unmodifiable set ofBluetoothDevice, or null on error

getDefaultAdapter

Added inAPI level 5
BluetoothAdapter getDefaultAdapter ()

Get a handle to the default local Bluetooth adapter.

Currently Android only supports one Bluetooth adapter, but the API could be extended to support more. This will always return the default adapter.

Returns BluetoothAdapter the default local adapter, or null if Bluetooth is not supported on this hardware platform

getName

Added inAPI level 5
String getName ()

Get the friendly Bluetooth name of the local Bluetooth adapter.

This name is visible to remote Bluetooth devices.

RequiresBLUETOOTH

Returns String the Bluetooth name, or null on error

getProfileConnectionState

Added inAPI level 14
int getProfileConnectionState (int profile)

Get the current connection state of a profile. This function can be used to check whether the local Bluetooth adapter is connected to any remote device for a specific profile. Profile can be one ofHEALTH,HEADSET,A2DP.

RequiresBLUETOOTH.

Return value can be one ofSTATE_DISCONNECTED,STATE_CONNECTING,STATE_CONNECTED,STATE_DISCONNECTING

Parameters profile int Returns int  

getProfileProxy

Added inAPI level 11
boolean getProfileProxy (Context context, 
                BluetoothProfile.ServiceListener listener, 
                int profile)

Get the profile proxy object associated with the profile.

Profile can be one ofHEALTH,HEADSET,A2DP,GATT, orGATT_SERVER. Clients must implementBluetoothProfile.ServiceListenerto get notified of the connection status and to get the proxy object.

Parameters context Context: Context of the application listener BluetoothProfile.ServiceListener: The service Listener for connection callbacks. profile int: The Bluetooth profile; eitherHEALTH,HEADSET,A2DP.GATTorGATT_SERVER. Returns boolean true on success, false on error

getRemoteDevice

Added inAPI level 16
BluetoothDevice getRemoteDevice (byte[] address)

Get aBluetoothDeviceobject for the given Bluetooth hardware address.

Valid Bluetooth hardware addresses must be 6 bytes. This method expects the address in network byte order (MSB first).

ABluetoothDevicewill always be returned for a valid hardware address, even if this adapter has never seen that device.

Parameters address byte: Bluetooth MAC address (6 bytes) Returns BluetoothDevice   Throws IllegalArgumentException if address is invalid

getRemoteDevice

Added inAPI level 5
BluetoothDevice getRemoteDevice (String address)

Get aBluetoothDeviceobject for the given Bluetooth hardware address.

Valid Bluetooth hardware addresses must be upper case, in a format such as "00:11:22:33:AA:BB". The helpercheckBluetoothAddress(String)is available to validate a Bluetooth address.

ABluetoothDevicewill always be returned for a valid hardware address, even if this adapter has never seen that device.

Parameters address String: valid Bluetooth MAC address Returns BluetoothDevice   Throws IllegalArgumentException if address is invalid

getScanMode

Added inAPI level 5
int getScanMode ()

Get the current Bluetooth scan mode of the local Bluetooth adapter.

The Bluetooth scan mode determines if the local adapter is connectable and/or discoverable from remote Bluetooth devices.

Possible values are:SCAN_MODE_NONE,SCAN_MODE_CONNECTABLE,SCAN_MODE_CONNECTABLE_DISCOVERABLE.

If Bluetooth state is notSTATE_ON, this API will returnSCAN_MODE_NONE. After turning on Bluetooth, wait forACTION_STATE_CHANGEDwithSTATE_ONto get the updated value.

RequiresBLUETOOTH

Returns int scan mode

getState

Added inAPI level 5
int getState ()

Get the current state of the local Bluetooth adapter.

Possible return values areSTATE_OFF,STATE_TURNING_ON,STATE_ON,STATE_TURNING_OFF.

RequiresBLUETOOTH

Returns int current state of Bluetooth adapter

isDiscovering

Added inAPI level 5
boolean isDiscovering ()

Return true if the local Bluetooth adapter is currently in the device discovery process.

Device discovery is a heavyweight procedure. New connections to remote Bluetooth devices should not be attempted while discovery is in progress, and existing connections will experience limited bandwidth and high latency. UsecancelDiscovery()to cancel an ongoing discovery.

Applications can also register forACTION_DISCOVERY_STARTEDorACTION_DISCOVERY_FINISHEDto be notified when discovery starts or completes.

If Bluetooth state is notSTATE_ON, this API will return false. After turning on Bluetooth, wait forACTION_STATE_CHANGEDwithSTATE_ONto get the updated value.

RequiresBLUETOOTH.

Returns boolean true if discovering

isEnabled

Added inAPI level 5
boolean isEnabled ()

Return true if Bluetooth is currently enabled and ready for use.

Equivalent to:getBluetoothState() == STATE_ON

RequiresBLUETOOTH

Returns boolean true if the local adapter is turned on

isMultipleAdvertisementSupported

Added inAPI level 21
boolean isMultipleAdvertisementSupported ()

Return true if the multi advertisement is supported by the chipset

Returns boolean true if Multiple Advertisement feature is supported

isOffloadedFilteringSupported

Added inAPI level 21
boolean isOffloadedFilteringSupported ()

Return true if offloaded filters are supported

Returns boolean true if chipset supports on-chip filtering

isOffloadedScanBatchingSupported

Added inAPI level 21
boolean isOffloadedScanBatchingSupported ()

Return true if offloaded scan batching is supported

Returns boolean true if chipset supports on-chip scan batching

listenUsingInsecureRfcommWithServiceRecord

Added inAPI level 10
BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord (String name, 
                UUID uuid)

Create a listening, insecure RFCOMM Bluetooth socket with Service Record.

The link key is not required to be authenticated, i.e the communication may be vulnerable to Man In the Middle attacks. For Bluetooth 2.1 devices, the link will be encrypted, as encryption is mandartory. For legacy devices (pre Bluetooth 2.1 devices) the link will not be encrypted. UselistenUsingRfcommWithServiceRecord(String, UUID), if an encrypted and authenticated communication channel is desired.

Useaccept()to retrieve incoming connections from a listeningBluetoothServerSocket.

The system will assign an unused RFCOMM channel to listen on.

The system will also register a Service Discovery Protocol (SDP) record with the local SDP server containing the specified UUID, service name, and auto-assigned channel. Remote Bluetooth devices can use the same UUID to query our SDP server and discover which channel to connect to. This SDP record will be removed when this socket is closed, or if this application closes unexpectedly.

UsecreateRfcommSocketToServiceRecord(UUID)to connect to this socket from another device using the sameUUID.

RequiresBLUETOOTH

Parameters name String: service name for SDP record uuid UUID: uuid for SDP record Returns BluetoothServerSocket a listening RFCOMM BluetoothServerSocket Throws IOException on error, for example Bluetooth not available, or insufficient permissions, or channel in use.

listenUsingRfcommWithServiceRecord

Added inAPI level 5
BluetoothServerSocket listenUsingRfcommWithServiceRecord (String name, 
                UUID uuid)

Create a listening, secure RFCOMM Bluetooth socket with Service Record.

A remote device connecting to this socket will be authenticated and communication on this socket will be encrypted.

Useaccept()to retrieve incoming connections from a listeningBluetoothServerSocket.

The system will assign an unused RFCOMM channel to listen on.

The system will also register a Service Discovery Protocol (SDP) record with the local SDP server containing the specified UUID, service name, and auto-assigned channel. Remote Bluetooth devices can use the same UUID to query our SDP server and discover which channel to connect to. This SDP record will be removed when this socket is closed, or if this application closes unexpectedly.

UsecreateRfcommSocketToServiceRecord(UUID)to connect to this socket from another device using the sameUUID.

RequiresBLUETOOTH

Parameters name String: service name for SDP record uuid UUID: uuid for SDP record Returns BluetoothServerSocket a listening RFCOMM BluetoothServerSocket Throws IOException on error, for example Bluetooth not available, or insufficient permissions, or channel in use.

setName

Added inAPI level 5
boolean setName (String name)

Set the friendly Bluetooth name of the local Bluetooth adapter.

This name is visible to remote Bluetooth devices.

Valid Bluetooth names are a maximum of 248 bytes using UTF-8 encoding, although many remote devices can only display the first 40 characters, and some may be limited to just 20.

If Bluetooth state is notSTATE_ON, this API will return false. After turning on Bluetooth, wait forACTION_STATE_CHANGEDwithSTATE_ONto get the updated value.

RequiresBLUETOOTH_ADMIN

Parameters name String: a valid Bluetooth name Returns boolean true if the name was set, false otherwise

startDiscovery

Added inAPI level 5
boolean startDiscovery ()

Start the remote device discovery process.

The discovery process usually involves an inquiry scan of about 12 seconds, followed by a page scan of each new device to retrieve its Bluetooth name.

This is an asynchronous call, it will return immediately. Register forACTION_DISCOVERY_STARTEDandACTION_DISCOVERY_FINISHEDintents to determine exactly when the discovery starts and completes. Register forACTION_FOUNDto be notified as remote Bluetooth devices are found.

Device discovery is a heavyweight procedure. New connections to remote Bluetooth devices should not be attempted while discovery is in progress, and existing connections will experience limited bandwidth and high latency. UsecancelDiscovery()to cancel an ongoing discovery. Discovery is not managed by the Activity, but is run as a system service, so an application should always callcancelDiscovery()even if it did not directly request a discovery, just to be sure.

Device discovery will only find remote devices that are currentlydiscoverable(inquiry scan enabled). Many Bluetooth devices are not discoverable by default, and need to be entered into a special mode.

If Bluetooth state is notSTATE_ON, this API will return false. After turning on Bluetooth, wait forACTION_STATE_CHANGEDwithSTATE_ONto get the updated value.

RequiresBLUETOOTH_ADMIN.

Returns boolean true on success, false on error

startLeScan

Added inAPI level 18
boolean startLeScan (UUID[] serviceUuids, 
                BluetoothAdapter.LeScanCallback callback)

 

This method was deprecated in API level 21.
usestartScan(List, ScanSettings, ScanCallback)instead.

Starts a scan for Bluetooth LE devices, looking for devices that advertise given services.

Devices which advertise all specified services are reported using theonLeScan(BluetoothDevice, int, byte[])callback.

RequiresBLUETOOTH_ADMINpermission.

Parameters serviceUuids UUID: Array of services to look for callback BluetoothAdapter.LeScanCallback: the callback LE scan results are delivered Returns boolean true, if the scan was started successfully

startLeScan

Added inAPI level 18
boolean startLeScan (BluetoothAdapter.LeScanCallback callback)

 

This method was deprecated in API level 21.
usestartScan(List, ScanSettings, ScanCallback)instead.

Starts a scan for Bluetooth LE devices.

Results of the scan are reported using theonLeScan(BluetoothDevice, int, byte[])callback.

RequiresBLUETOOTH_ADMINpermission.

Parameters callback BluetoothAdapter.LeScanCallback: the callback LE scan results are delivered Returns boolean true, if the scan was started successfully

stopLeScan

Added inAPI level 18
void stopLeScan (BluetoothAdapter.LeScanCallback callback)

 

This method was deprecated in API level 21.
UsestopScan(ScanCallback)instead.

Stops an ongoing Bluetooth LE device scan.

RequiresBLUETOOTH_ADMINpermission.

Parameters callback BluetoothAdapter.LeScanCallback: used to identify which scan to stop must be the same handle used to start the scan

Protected methods


finalize

Added inAPI level 5
void finalize ()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides thefinalizemethod to dispose of system resources or to perform other cleanup.

The general contract offinalizeis that it is invoked if and when the JavaTMvirtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized. Thefinalizemethod may take any action, including making this object available again to other threads; the usual purpose offinalize, however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection before the object is permanently discarded.

Thefinalizemethod of classObjectperforms no special action; it simply returns normally. Subclasses ofObjectmay override this definition.

The Java programming language does not guarantee which thread will invoke thefinalizemethod for any given object. It is guaranteed, however, that the thread that invokes finalize will not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.

After thefinalizemethod has been invoked for an object, no further action is taken until the Java virtual machine has again determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, including possible actions by other objects or classes which are ready to be finalized, at which point the object may be discarded.

Thefinalizemethod is never invoked more than once by a Java virtual machine for any given object.

Any exception thrown by thefinalizemethod causes the finalization of this object to be halted, but is otherwise ignored.

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved