如何修复Fragment中registerReceiver()的null返回,同样的代码在Activity中工作

问题描述 投票:0回答:1

问题出在Fragment中,它使用USB服务,并且在调试时始终为null时无法注册返回的服务。

我有USB服务,它在Activity中工作得很好,然后我改变了代码在片段中工作,所以我可以使用ViewPager ..现在问题,USB服务总是返回null,我已经应用了相同的代码,但似乎片段需要其他工作比活动,我仍然没有抓住和这里。这是添加服务类后的片段代码,并在清单中提及它。

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;
         }
       }
    }
 }
java android broadcastreceiver android-broadcast
1个回答
0
投票

这是因为你在打电话:

usbService.registerReceiver(mUsbReceiver,  filter);

在启动服务之前,您已在以下行中完成此操作:

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ...

    setFilters();  // Start listening notifications from UsbService
    startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
    return rootView;
}

所以,你只需要翻转代码来解决问题:

startService(UsbService.class, usbConnection, null);
setFilters();
© www.soinside.com 2019 - 2024. All rights reserved.