如何修复Fragment中registerReceiver()的空返回,并且相同的代码在Activity中正常工作

时间:2019-02-18 09:12:14

标签: java android broadcastreceiver android-broadcast

片段中存在问题,该片段消耗USB服务,并且在调试始终为null时无法注册返回的服务。

我有USB Service,在Activity中可以正常工作,然后我将代码更改为可分段运行,因此可以使用ViewPager .. 现在,USB服务总是返回null的问题,我已经应用了相同的代码,但是片段似乎需要除Activity之外的其他工作,而我仍然没有抓住,这里是。 这是添加服务类并在清单中提及后的片段代码。

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;
         }
       }
    }
 }

1 个答案:

答案 0 :(得分: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();