Android uses feature bluetooth

Bluetooth overview

The Android platform includes support for the Bluetooth network stack, which allows a device to wirelessly exchange data with other Bluetooth devices. The app framework provides access to the Bluetooth functionality through Bluetooth APIs. These APIs let apps connect to other Bluetooth devices, enabling point-to-point and multipoint wireless features.

Using the Bluetooth APIs, an app can perform the following:

  • Scan for other Bluetooth devices.
  • Query the local Bluetooth adapter for paired Bluetooth devices.
  • Establish RFCOMM channels.
  • Connect to other devices through service discovery.
  • Transfer data to and from other devices.
  • Manage multiple connections.

This topic focuses on Classic Bluetooth. Classic Bluetooth is the right choice for more battery-intensive operations, which include streaming and communicating between devices. For Bluetooth devices with low power requirements, consider using Bluetooth Low Energy connections.

This documentation describes different Bluetooth profiles and explains how to use the Bluetooth APIs to accomplish the four major tasks necessary to communicate using Bluetooth:

  • Setting up Bluetooth.
  • Finding devices that are either paired or available in the local area.
  • Connecting devices.
  • Transferring data between devices.

For a demonstration of using the Bluetooth APIs, see the Bluetooth Chat sample app.

The basics

For Bluetooth-enabled devices to transmit data between each other, they must first form a channel of communication using a pairing process. One device, a discoverable device, makes itself available for incoming connection requests. Another device finds the discoverable device using a service discovery process. After the discoverable device accepts the pairing request, the two devices complete a bonding process in which they exchange security keys. The devices cache these keys for later use. After the pairing and bonding processes are complete, the two devices exchange information. When the session is complete, the device that initiated the pairing request releases the channel that had linked it to the discoverable device. The two devices remain bonded, however, so they can reconnect automatically during a future session as long as they’re in range of each other and neither device has removed the bond.

Use of the Bluetooth APIs requires declaring several permissions in your manifest file. Once your app has permission to use Bluetooth, your app needs to access the BluetoothAdapter and determine if Bluetooth is available on the device. If Bluetooth is available, there are three steps to make a connection:

Certain devices use a specific Bluetooth profile that declares the data it provides.

Key classes and interfaces

All of the Bluetooth APIs are available in the android.bluetooth package. The following are the classes and interfaces you need in order to create Bluetooth connections:

BluetoothAdapter Represents the local Bluetooth adapter (Bluetooth radio). The BluetoothAdapter is the entry-point for all Bluetooth interaction. Using this, you can discover other Bluetooth devices, query a list of bonded (paired) devices, instantiate a BluetoothDevice using a known MAC address, and create a BluetoothServerSocket to listen for communications from other devices. BluetoothDevice Represents a remote Bluetooth device. Use this to request a connection with a remote device through a BluetoothSocket or query information about the device such as its name, address, class, and bonding state. BluetoothSocket Represents the interface for a Bluetooth socket (similar to a TCP Socket ). This is the connection point that allows an app to exchange data with another Bluetooth device using InputStream and OutputStream . BluetoothServerSocket Represents an open server socket that listens for incoming requests (similar to a TCP ServerSocket ). In order to connect two devices, one device must open a server socket with this class. When a remote Bluetooth device makes a connection request to this device, the device accepts the connection and then returns a connected BluetoothSocket . BluetoothClass Describes the general characteristics and capabilities of a Bluetooth device. This is a read-only set of properties that defines the device’s classes and services. Although this information provides a useful hint regarding a device’s type, the attributes of this class don’t necessarily describe all Bluetooth profiles and services that the device supports. BluetoothProfile An interface that represents a Bluetooth profile. A Bluetooth profile is a wireless interface specification for Bluetooth-based communication between devices. An example is the Hands-Free profile. For more discussion of profiles, see Bluetooth profiles. BluetoothHeadset Provides support for Bluetooth headsets to be used with mobile phones. This includes both the Bluetooth Headset profile and the Hands-Free (v1.5) profile. BluetoothA2dp Defines how high-quality audio can be streamed from one device to another over a Bluetooth connection using the Advanced Audio Distribution Profile (A2DP). BluetoothHealth Represents a Health Device Profile proxy that controls the Bluetooth service. BluetoothHealthCallback An abstract class that you use to implement BluetoothHealth callbacks. You must extend this class and implement the callback methods to receive updates about changes in the app’s registration state and Bluetooth channel state. BluetoothHealthAppConfiguration Represents an app configuration that the Bluetooth Health third-party app registers to communicate with a remote Bluetooth health device. BluetoothProfile.ServiceListener An interface that notifies BluetoothProfile interprocess communication (IPC) clients when they have been connected to or disconnected from the internal service that runs a particular profile.

Читайте также:  Самые лучшие портативные колонки блютуз

Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.

Last updated 2021-10-27 UTC.

Источник

I’m try to grant access to Enable and Disable Bluetooth on Android Studio using JAVA; but startActivityForResult has been Deprecated. What I can do? [duplicate]

I would like grant access to Enable and Disable Bluetooth from Android Studio. I also pretend to use other functionalities of Bluetooth as list of devices and connect to previous pared device and more. Since starActivityForResult has been Deprecated, I’m having trouble to lunch the pop up activity that ask the user for allowance. This is my manifest

package com.example.bluetoothexamples; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.Set; public class MainActivity extends AppCompatActivity implements View.OnClickListener < private static final int REQUEST_ENABLE_BT = 0; private static final int REQUEST_DISCOVER_BT = 1; TextView mStatusBlueTv; TextView mPairedTv; ImageView mBlueIv; Button mOnBtn; Button mOffBtn; Button mDiscoverBtn; Button mPairedBtn; BluetoothAdapter mBlueAdapter; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mStatusBlueTv = findViewById(R.id.statusBluetoothTv); mPairedTv = findViewById(R.id.pairedTv); mBlueIv = findViewById(R.id.bluetoothIv); mOnBtn = findViewById(R.id.onBtn); mOffBtn = findViewById(R.id.offBtn); mDiscoverBtn = findViewById(R.id.discoverableBtn); mPairedBtn = findViewById(R.id.pairedBtn); // Adapter mBlueAdapter = BluetoothAdapter.getDefaultAdapter(); //Check if bluetooth is available or not if (mBlueAdapter == null) < mStatusBlueTv.setText("Bluetooth is NOT Available"); >else < mStatusBlueTv.setText("Bluetooth is Available"); // Set image according to bluetooth status (on/off) if (mBlueAdapter.isEnabled()) < mBlueIv.setImageResource(R.drawable.ic_action_on); >else < mBlueIv.setImageResource(R.drawable.ic_action_off); >mOnBtn.setOnClickListener(this); // Turn on Bluetooth btn click mDiscoverBtn.setOnClickListener(this); // Discover bluetooth btn click mOffBtn.setOnClickListener(this); // Turn off Bluetooth btn click mPairedBtn.setOnClickListener(this); // Get Paired devices button click > > @Override public void onClick(View view) < switch (view.getId()) < // Turn on Bluetooth btn click case R.id.onBtn: if (!mBlueAdapter.isEnabled()) < // showToast("Turning On Bluetooth. "); // if (getApplicationContext().checkSelfPermission(Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) < // >else < // requestPermissions(new String[],1); // > if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) < // TODO: Consider calling ActivityCompat.requestPermissions(MainActivity.this, new String[],1); // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; > // Intent to On Bluetooth Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, REQUEST_ENABLE_BT); > else < showToast("Bluetooth is already on"); >break; // Discover bluetooth btn click case R.id.discoverableBtn: if (!mBlueAdapter.isDiscovering()) < showToast("Making Your Device Discoverable"); Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); startActivityForResult(intent ,REQUEST_DISCOVER_BT); >break; // Turn off Bluetooth btn click case R.id.offBtn: if (mBlueAdapter.isEnabled()) < mBlueAdapter.disable(); showToast("Turning Bluetooth Off"); mBlueIv.setImageResource(R.drawable.ic_action_off); >else < showToast("Bluetooth is already off"); >break; // Get Paired devices button click case R.id.pairedBtn: if (mBlueAdapter.isEnabled()) < mPairedTv.setText("Paired Devices"); Setdevices = mBlueAdapter.getBondedDevices(); for (BluetoothDevice device: devices) < mPairedTv.append("\nDevice: " + device.getName() + ", " + device); >> else < //bluetooth is off so can't get paired devices showToast("Turn ON Bluetooth to get paired devices"); >break; > > @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) < super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 1)< if (grantResults[0] == PackageManager.PERMISSION_GRANTED)< showToast("Permission Granted"); >else < showToast("Permission Denied"); >> > @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) < switch (requestCode)< case REQUEST_ENABLE_BT: if (resultCode == RESULT_OK) < // Bluetooth is on mBlueIv.setImageResource(R.drawable.ic_action_on); showToast("Bluetooth is on"); >else < showToast("Failed to connect to bluetooth"); >break; > super.onActivityResult(requestCode, resultCode, data); > //Toast message function private void showToast (String msg) < Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); >> 

1 Answer 1

Currently the recommended approach is using a ActivityResultLauncher to get the results like so:

ActivityResultLauncher activityResultLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> < if (result.getResultCode() == Activity.RESULT_OK) < Log.e("Activity result","OK"); // There are no request codes Intent data = result.getData(); >>); 
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); activityResultLauncher.launch(intent); 

and for your case assuming everything else is working fine ,you update to something like below:

package com.example.bluetoothexamples; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.activity.result.ActivityResultLauncher; import android.app.Activity; import android.util.Log; import java.util.Set; public class MainActivity extends AppCompatActivity implements View.OnClickListener < private static final int REQUEST_ENABLE_BT = 0; private static final int REQUEST_DISCOVER_BT = 1; TextView mStatusBlueTv; TextView mPairedTv; ImageView mBlueIv; Button mOnBtn; Button mOffBtn; Button mDiscoverBtn; Button mPairedBtn; BluetoothAdapter mBlueAdapter; ActivityResultLauncheractivityResultLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> < if (result.getResultCode() == Activity.RESULT_OK) < Log.e("Activity result","OK"); // There are no request codes Intent data = result.getData(); >>); @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mStatusBlueTv = findViewById(R.id.statusBluetoothTv); mPairedTv = findViewById(R.id.pairedTv); mBlueIv = findViewById(R.id.bluetoothIv); mOnBtn = findViewById(R.id.onBtn); mOffBtn = findViewById(R.id.offBtn); mDiscoverBtn = findViewById(R.id.discoverableBtn); mPairedBtn = findViewById(R.id.pairedBtn); // Adapter mBlueAdapter = BluetoothAdapter.getDefaultAdapter(); //Check if bluetooth is available or not if (mBlueAdapter == null) < mStatusBlueTv.setText("Bluetooth is NOT Available"); >else < mStatusBlueTv.setText("Bluetooth is Available"); // Set image according to bluetooth status (on/off) if (mBlueAdapter.isEnabled()) < mBlueIv.setImageResource(R.drawable.ic_action_on); >else < mBlueIv.setImageResource(R.drawable.ic_action_off); >mOnBtn.setOnClickListener(this); // Turn on Bluetooth btn click mDiscoverBtn.setOnClickListener(this); // Discover bluetooth btn click mOffBtn.setOnClickListener(this); // Turn off Bluetooth btn click mPairedBtn.setOnClickListener(this); // Get Paired devices button click > > @Override public void onClick(View view) < switch (view.getId()) < // Turn on Bluetooth btn click case R.id.onBtn: if (!mBlueAdapter.isEnabled()) < // showToast("Turning On Bluetooth. "); // if (getApplicationContext().checkSelfPermission(Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) < // >else < // requestPermissions(new String[],1); // > if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) < // TODO: Consider calling ActivityCompat.requestPermissions(MainActivity.this, new String[],1); // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; > // Intent to On Bluetooth Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // startActivityForResult(intent, REQUEST_ENABLE_BT); activityResultLauncher.launch(intent); > else < showToast("Bluetooth is already on"); >break; // Discover bluetooth btn click case R.id.discoverableBtn: if (!mBlueAdapter.isDiscovering()) < showToast("Making Your Device Discoverable"); Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); //startActivityForResult(intent ,REQUEST_DISCOVER_BT); activityResultLauncher.launch(intent); >break; // Turn off Bluetooth btn click case R.id.offBtn: if (mBlueAdapter.isEnabled()) < mBlueAdapter.disable(); showToast("Turning Bluetooth Off"); mBlueIv.setImageResource(R.drawable.ic_action_off); >else < showToast("Bluetooth is already off"); >break; // Get Paired devices button click case R.id.pairedBtn: if (mBlueAdapter.isEnabled()) < mPairedTv.setText("Paired Devices"); Setdevices = mBlueAdapter.getBondedDevices(); for (BluetoothDevice device: devices) < mPairedTv.append("\nDevice: " + device.getName() + ", " + device); >> else < //bluetooth is off so can't get paired devices showToast("Turn ON Bluetooth to get paired devices"); >break; > > @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) < super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 1)< if (grantResults[0] == PackageManager.PERMISSION_GRANTED)< showToast("Permission Granted"); >else < showToast("Permission Denied"); >> > @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) < switch (requestCode)< case REQUEST_ENABLE_BT: if (resultCode == RESULT_OK) < // Bluetooth is on mBlueIv.setImageResource(R.drawable.ic_action_on); showToast("Bluetooth is on"); >else < showToast("Failed to connect to bluetooth"); >break; > super.onActivityResult(requestCode, resultCode, data); > //Toast message function private void showToast (String msg) < Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); >> 
 ActivityResultLauncher activityResultLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback() < @Override public void onActivityResult(ActivityResult result) < if (result.getResultCode() == Activity.RESULT_OK) < Log.e("Activity result", "OK"); // There are no request codes Intent data = result.getData(); >> > ); 

Источник

Оцените статью
Adblock
detector