【发布时间】:2020-05-14 08:54:19
【问题描述】:
我有一个应用程序可以通过蓝牙接收数据。这个想法是我有一个在后台运行的蓝牙服务,它绑定到主要活动。当在片段上按下按钮时会创建服务(我将服务绑定到活动,因为我想保持蓝牙连接,即使片段已损坏。)
为此,当按下片段中的按钮时,我将片段中的处理程序传递给活动,然后将处理程序传递给服务,以便我可以根据接收到的数据更新片段 UI .
但是,我得到了 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;
}
};
片段:
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);
}
}
};
【问题讨论】:
-
您可以使用接口回调将您的处理程序传回活动
标签: android android-fragments static