我有一个通过蓝牙接收数据的应用,我的想法是在后台运行一个蓝牙服务,它与主活动绑定。我的想法是,我有一个蓝牙服务在后台运行,它被绑定到主活动上。当一个片段上的按钮被按下时,这个服务就会被创建(我把服务绑定到活动上,因为我想保持蓝牙连接,即使片段已经损坏。
为此,当片段中的按钮被按下时,我将处理程序从片段传递给活动,处理程序将被传递给服务,这样我就可以根据收到的数据更新片段的用户界面。
然而,我得到了 non-static method cannot be reference from a static context
对于 getBTService
我无法解决它,因为我不能使它的 bindService
静态的。谁能给点建议?或者有什么更好的管理方法吗?下面是相关代码。
主活动:
public void getBTService(Handler btHandler){
this.mHandler = btHandler;
Intent intent = new Intent(this, BluetoothService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (btService != null) {
unbindService(connection);
btBound = false;
}
}
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
btService = binder.getService(mHandler);
btBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
btBound = false;
}
};
Fragment:
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_signal, container, false);
statusTV = root.findViewById(R.id.text_status);
dataTV = root.findViewById(R.id.text_data);\
openBtn = root.findViewById(R.id.openBtn);
mChart = root.findViewById(R.id.chart);
openBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
MainActivity.getBTService(mHandler);
}
}
);
return root;
}
private final Handler mHandler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
switch ((msg.what)){
case MainActivity.MessageConstants.MESSAGE_READ:
String data = (String) msg.obj;
updateTV("data", data);
}
}
};
你可以尝试这样做,而不是直接调用 MainActivity
openBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
((MainActivity) requireActivity()).getBTService(mHandler);
}
}