Проблема во фрагменте, который использует службу USB и не может зарегистрировать службу, возвращающуюся при отладке, всегда равной нулю.
У меня есть служба USB, которая полностью работает в Activity, затем я изменил код для работы вфрагмент, так что я могу использовать ViewPager .. Теперь проблема в том, что служба USB всегда возвращает ноль, и я применил один и тот же код, но кажется, что фрагмент требует другой работы, чем активность, которую я до сих пор не поймал, и вот.Вот фрагмент кода после добавления класса обслуживания и упомяните его в манифесте.
public class RealTimeFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
TextView tvTimeStamp, tvPm25, tvPm10, tvTemp, tvHumid, tvCo2, tvTvoc, tvNoise, tvPa;
RoundCornerProgressBar pbPm25, pbPm10, pbTemp, pbHumid, pbCo2, pbTvoc, pbNoise, pbPa;
ImageView ivVent ;
public static final String TAG = "MainActivity";
private UsbService usbService;
private RealTimeFragment.MyHandler mHandler;
static String myJson = "";
static int dbCount = 0;
static ControlViewModel controlViewModel;
static View mView;
private final ServiceConnection usbConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
usbService.changeBaudRate(9600);
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
/*
* Notifications from UsbService will be received here.
*/
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action!=null) {
switch (action) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
}
};
public RealTimeFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static RealTimeFragment newInstance(int sectionNumber) {
RealTimeFragment fragment = new RealTimeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.realtime_layout_fragment, container, false);
tvTimeStamp = rootView.findViewById(R.id.tv_serial_output);
tvPm25 = rootView.findViewById(R.id.tv_pm25);
pbPm25 = rootView.findViewById(R.id.pb_pm25);
tvPm10 = rootView.findViewById(R.id.tv_pm10);
pbPm10 = rootView.findViewById(R.id.pb_pm10);
tvTemp = rootView.findViewById(R.id.tv_temp);
pbTemp = rootView.findViewById(R.id.pb_temp);
tvHumid = rootView.findViewById(R.id.tv_humid);
pbHumid = rootView.findViewById(R.id.pb_humid);
tvCo2 = rootView.findViewById(R.id.tv_co2);
pbCo2 = rootView.findViewById(R.id.pb_co2);
tvTvoc = rootView.findViewById(R.id.tv_tvoc);
pbTvoc = rootView.findViewById(R.id.pb_tvoc);
tvNoise = rootView.findViewById(R.id.tv_noise);
pbNoise = rootView.findViewById(R.id.pb_noise);
tvPa = rootView.findViewById(R.id.tv_pressure);
pbPa = rootView.findViewById(R.id.pb_pressure);
ivVent = rootView.findViewById(R.id.iv_vent);
mHandler = new RealTimeFragment.MyHandler(getActivity());
//assert getArguments() != null;
//textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
this.mView = rootView;
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
return rootView;
}
@Override
public void onResume() {
super.onResume();
// setFilters(); // Start listening notifications from UsbService
// startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
@Override
public void onPause() {
super.onPause();
usbService.unregisterReceiver(mUsbReceiver);
usbService.unbindService(usbConnection);
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(getContext(), service);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
usbService.startService(startService);
}
Intent bindingIntent = new Intent(getContext(), service);
usbService.bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
Log.e("startService",mUsbReceiver.toString());
usbService.registerReceiver(mUsbReceiver, filter);
// LocalBroadcastManager.getInstance(usbService).registerReceiver(mUsbReceiver, filter);
}
/*
* This handler will be passed to UsbService. Data received from serial port is displayed through this handler
*/
private static class MyHandler extends Handler {
private final WeakReference<Activity> mActivity;
private MyHandler(Activity activity) {
mActivity = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String buffer = (String) msg.obj;
myJson += buffer;
if (buffer.indexOf('}') >= 0) {
try {
Data responseBegin = new Gson().fromJson(myJson, Data.class);
SystemControl systemControl = new SystemControl(responseBegin.getStaticFilter() == 1 ? true:false, responseBegin.getAutoVent() == 1 ? true:false, responseBegin.getFanSpeed());
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
controlViewModel.getSystemControl().postValue(systemControl);
updateUI(responseBegin);
myJson = "";
} catch (Exception e) {
myJson = "";
}
}
break;
case UsbService.CTS_CHANGE:
Toast.makeText(mActivity.get(), "CTS_CHANGE", Toast.LENGTH_LONG).show();
break;
case UsbService.DSR_CHANGE:
Toast.makeText(mActivity.get(), "DSR_CHANGE", Toast.LENGTH_LONG).show();
break;
case UsbService.SYNC_READ:
String buffer2 = (String) msg.obj;
myJson += buffer2;
if (buffer2.indexOf('}') >= 0) {
try {
Data responseBegin = new Gson().fromJson(myJson, Data.class);
SystemControl systemControl = new SystemControl(responseBegin.getStaticFilter() == 1 ? true:false, responseBegin.getAutoVent() == 1 ? true:false, responseBegin.getFanSpeed());
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer. controlViewModel.getSystemControl().postValue(systemControl);
updateUI(responseBegin);
myJson = "";
} catch (Exception e) {
myJson = "";
}
}
break;
}
}
}
}