这是我的应用程序:它执行蓝牙扫描,并且扫描功能在找到设备时会回调。我想将特定按钮的文本从“搜索”更改为“连接”,因为它找到了特定的设备(可以通过其设备名称识别出该设备)。
但是,该按钮在回调范围内不可用。
有什么办法吗?我认为这纯粹是一个范围问题,对这种事情我几乎没有经验。
代码 :
Context context;
context = this;
update_str = "";
Button ConnectButton = (Button) findViewById(R.id.Connect);
ConnectButton.setText("Waiting for device to be found");
Button ScanButton = (Button) findViewById(R.id.Scan);
ScanButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btAdapter.startLeScan(leScanCallback);
}
});
BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
update_str = update_str.concat(" " + device.getName());
((TextView)findViewById (R.id.text)).setText (update_str);
nom_device = device.getName();
if (nom_device=="bill_gates"){
context.ConnectButton.setText(nom_device);
context.ConnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
BluetoothGatt bluetoothGatt = device.connectGatt(getApplicationContext(), false, context.btleGattCallback);
}
});
}
}
};
编译器错误日志:
C:\Code\Grizz\app\src\main\java\com\grizz\grizzmvp\MainActivity.java
Error:(84, 28) error: cannot find symbol variable ConnectButton
Error:(89, 117) error: cannot find symbol variable btleGattCallback
Error:(86, 28) error: cannot find symbol variable ConnectButton
Note: C:\Code\Grizz\app\src\main\java\com\grizz\grizzmvp\MainActivity.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Error:Execution failed for task ':app:compileDebugJava'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED
Information:Total time: 1.381 secs
Information:4 errors
Information:0 warnings
Information:See complete output in console
当在方法主体中定义匿名内部类时,可以从内部类内部访问在该方法范围内声明为final的所有变量。对于标量值,一旦将其赋值,最终变量的值就无法更改。对于对象值,引用不能更改。这允许Java编译器在运行时“捕获”变量的值,并将副本存储为内部类中的字段。一旦外部方法终止并删除了其堆栈框架,原始变量就消失了,但是内部类的私有副本仍保留在该类自己的内存中。
final Button ConnectButton = (Button) findViewById(R.id.Connect);
ConnectButton.setText("Waiting for device to be found");
final Button ScanButton = (Button) findViewById(R.id.Scan);
ScanButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btAdapter.startLeScan(leScanCallback);
}
});
BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
update_str = update_str.concat(" " + device.getName());
((TextView)findViewById (R.id.text)).setText (update_str);
nom_device = device.getName();
if (nom_device.equals("bill_gates")){
ConnectButton.setText(nom_device);
ConnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
BluetoothGatt bluetoothGatt = device.connectGatt(getApplicationContext(), false, context.btleGattCallback);
}
});
}
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句