我在Arduino Atmega 2560上安装了Bluetooth 4.0 BLE,并且我需要使用应用Android(我是Android Studio制造的)来扫描存储库并发送数据,将“ 1”发送到on led,将“ 0”发送到off led ,但是此代码需要保留在片段上。这是APP的类片段的源代码:
扫描设备的方法不起作用,很多错误...
示例:“无法解析leScanCallback”
存在在片段布局中使用BLE的问题吗?我只需要发送,将来就可以从Android设备和Arduino设备之间的通信中接收数据。
我添加了方法私有LeDeviceListAdapter leDeviceListAdapter;但是仍然无法解决的错误对我来说现在返回到“ LeDeviceListAdapter”;
public class ManejoFragment extends Fragment {
private final static int REQUEST_ENABLE_BT = 1;
private ManejoViewModel manejoViewModel;
private Button btnLigarDesligar;
private BluetoothAdapter bluetoothAdapter;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
manejoViewModel =
ViewModelProviders.of(this).get(ManejoViewModel.class);
View root = inflater.inflate(R.layout.fragment_tela_manejo, container, false);
final TextView textView = root.findViewById(R.id.text_tools);
manejoViewModel.getText().observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String s) { // Puxa o texto definido na classe anterior e mostra na tela de Manejo
textView.setText(s);
}
});
final BluetoothManager bluetoothManager =
(BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
if(!bluetoothAdapter.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
btnLigarDesligar = (Button)root.findViewById(R.id.botaoLigarDesligar);
btnLigarDesligar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
return root;
}
} ```
``` java
public class DeviceScanActivity extends ListActivity {
private BluetoothAdapter bluetoothAdapter;
private boolean mScanning;
private Handler handler;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
handler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
bluetoothAdapter.stopLeScan(leScanCallback);
}
}, SCAN_PERIOD);
mScanning = true;
bluetoothAdapter.startLeScan(leScanCallback);
} else {
mScanning = false;
bluetoothAdapter.stopLeScan(leScanCallback);
}
}
}```
private LeDeviceListAdapter leDeviceListAdapter;
// Device scan callback.
private BluetoothAdapter.LeScanCallback leScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
leDeviceListAdapter.addDevice(device);
leDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
}
AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
TestActivity.kt:
import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.AsyncTask
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.test_layout.*
class TestActivity : AppCompatActivity() {
private var btScanner: BluetoothLeScanner? = null
private var btManager: BluetoothManager? = null
private var btAdapter: BluetoothAdapter? = null
private var isScanning = false
private val REQUEST_ENABLE_BT = 1
private val PERMISSION_REQUEST_COARSE_LOCATION = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.test_layout)
btManager = getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager
btAdapter = btManager?.adapter
btScanner = btAdapter?.bluetoothLeScanner
if (btAdapter != null && !btAdapter!!.isEnabled) {
val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableIntent, REQUEST_ENABLE_BT)
}
// Make sure we have access coarse location enabled, if not, prompt the user to enable it
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
val builder =
AlertDialog.Builder(this)
builder.setTitle("This app needs location access")
builder.setMessage("Please grant location access so this app can detect peripherals.")
builder.setPositiveButton("ok", null)
builder.setOnDismissListener {
requestPermissions(
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
PERMISSION_REQUEST_COARSE_LOCATION
)
}
builder.show()
}
button.setOnClickListener {
if (isScanning) {
stopScanning()
} else {
startScanning()
}
}
}
// Device scan callback.
private val leScanCallback: ScanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
editText.append("Device Name: " + result.device?.name?.toString() + " rssi: " + result.rssi.toString() + "\n")
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
when (requestCode) {
PERMISSION_REQUEST_COARSE_LOCATION -> {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
println("coarse location permission granted")
} else {
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
builder.setTitle("Functionality limited")
builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.")
builder.setPositiveButton("OK", null)
builder.show()
}
return
}
}
}
private fun startScanning() {
println("start scanning")
isScanning = true
AsyncTask.execute { btScanner?.startScan(leScanCallback) }
}
private fun stopScanning() {
println("stopping scanning")
isScanning = false
AsyncTask.execute { btScanner?.stopScan(leScanCallback) }
}
}
test_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:text="Start/Stop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="@+id/editText"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:ems="10"
android:gravity="start|top"
android:inputType="textMultiLine"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>