广播管理器不在Fragment中工作

时间:2019-03-24 12:58:56

标签: java android android-fragments android-fragmentactivity

我有一个BroadcastReceiver,用于从BLE设备接收数据。相同的代码在Activity中工作正常,但在Fragment中工作不正常。

代码如下:

    public class HomeFragment extends Fragment implements LocationListener {

    Session session;
    TextView textViewName;
    TextView textViewSteps;
    TextView textViewCalories;
    TextView textViewDistance;
    TextView textViewFimos;
    ImageView imageViewInfo;
    public static final String TAG = "StepCounter";

    private UARTService mService = null;
    private BluetoothDevice evolutionDevice = null;

    private static final int UART_PROFILE_CONNECTED = 20;
    private static final int UART_PROFILE_DISCONNECTED = 21;
    private int mState = UART_PROFILE_DISCONNECTED;

    MyDatabase myDatabase;
    LocationManager service;
    private LocationManager locationManager;
    private String provider;
    double latitude, longitude;
    List<Byte> listBytes = new ArrayList<>();
    int rowNumber = 1;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        init(view);

        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        service_init();
    }

    private void init(View view) {

        session = new Session(getActivity());

        myDatabase = new MyDatabase(getActivity());

        service = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);

        if (!enabled) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }

        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);

        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
            System.out.println("Provider " + provider + " has been selected.");
            onLocationChanged(location);
        }


        textViewName = view.findViewById(R.id.textViewName);
        textViewSteps = view.findViewById(R.id.textViewSteps);
        textViewCalories = view.findViewById(R.id.textViewCalories);
        textViewDistance = view.findViewById(R.id.textViewDistance);
        textViewFimos = view.findViewById(R.id.textViewFimos);
        imageViewInfo = view.findViewById(R.id.imageViewInfo);

        try {
            textViewName.setText("Hi, " + session.getUser().getUser().getName());
        } catch (Exception e) {

        }

    }

    private void service_init() {
        System.out.println("---->>>>");
        Intent bindIntent = new Intent(getActivity().getApplicationContext(), UARTService.class);
        getActivity().bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);

        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder rawBinder) {
            mService = ((UARTService.LocalBinder) rawBinder).getService();
            Log.d(TAG, "onServiceConnected mService= " + mService);
            if (!mService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                getActivity().finish();
            }

        }

        public void onServiceDisconnected(ComponentName classname) {
            mService = null;
        }
    };

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UARTService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(UARTService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(UARTService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(UARTService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(UARTService.DEVICE_DOES_NOT_SUPPORT_UART);
        return intentFilter;
    }

    private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            final Intent mIntent = intent;
            //*********************//
            if (action.equals(UARTService.ACTION_GATT_CONNECTED)) {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        System.out.println("------- Device Connected: " + evolutionDevice.getName() + " - " + evolutionDevice.getAddress());
                        mState = UART_PROFILE_CONNECTED;
                    }
                });
            }

            //*********************//
            if (action.equals(UARTService.ACTION_GATT_DISCONNECTED)) {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        System.out.println("------- Device Disconnected");
                        mState = UART_PROFILE_DISCONNECTED;
                        mService.close();
                        evolutionDevice = null;
                    }
                });
            }

            //*********************//
            if (action.equals(UARTService.ACTION_GATT_SERVICES_DISCOVERED)) {
                mService.enableTXNotification();
            }
            //*********************//
            if (action.equals(UARTService.ACTION_DATA_AVAILABLE)) {
                final byte[] txValue = intent.getByteArrayExtra(UARTService.EXTRA_DATA);
                List<Byte> byteList = Bytes.asList(txValue);
                combineArrays(byteList);
            }
            //*********************//
            if (action.equals(UARTService.DEVICE_DOES_NOT_SUPPORT_UART)) {
                System.out.println("------- Device doesn't support UART. Disconnecting");
                mService.disconnect();
            }


        }
    };

    @Override
    public void onResume() {
        super.onResume();

        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.requestLocationUpdates(provider, 400, 1, this);
        Log.d(TAG, "onResume");
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy()");

        try {
            LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(UARTStatusChangeReceiver);
        } catch (Exception ignore) {
            Log.e(TAG, ignore.toString());
        }
        getActivity().unbindService(mServiceConnection);
        mService.stopSelf();
        mService = null;

    }

完整的代码相同,但在Activity中的一些工作正常。任何想法可能是阻止者。我是否需要在片段中执行其他操作才能从本地广播管理器接收数据?

3 个答案:

答案 0 :(得分:1)

请尝试这种方式: 创建类BroadcastHelper

public class BroadcastHelper {
    public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
    public static final String ACTION_NAME = "hossam";

    public static void sendInform(Context context, String method) {
        Intent intent = new Intent();
        intent.setAction(ACTION_NAME);
        intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
        try {
            context.sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void sendInform(Context context, String method, Intent intent) {
        intent.setAction(ACTION_NAME);
        intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
        try {
            context.sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在您的fragment中:

private Receiver receiver;
private boolean isReciverRegistered = false;


@Override
public void onResume() {
    super.onResume();
    if (receiver == null) {
        receiver = new Receiver();
        IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
        getActivity().registerReceiver(receiver, filter);
        isReciverRegistered = true;
    }
}

@Override
public void onDestroy() {
    if (isReciverRegistered) {
        if (receiver != null)
            getActivity().unregisterReceiver(receiver);
    }
    super.onDestroy();
}

private class Receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context arg0, Intent arg1) {
        Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
        String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
        if (methodName != null && methodName.length() > 0) {
            Log.v("receive", methodName);
            switch (methodName) {

                case "Test":
                    Toast.makeText(getActivity(), "message", Toast.LENGTH_SHORT).show();
                    break;

                default:
                    break;

            }
        }
    }
}

然后将此代码发送给广播:

BroadcastHelper.sendInform(context, "Test");

或者,如果您要使用它发送数据,请使用:

Intent intent = new Intent("intent");
intent.putExtra("desc", desc);
intent.putExtra("name", Local_name);
intent.putExtra("code", productCode);
BroadcastHelper.sendInform(getActivity(), "Test" , intent);

答案 1 :(得分:0)

我有一个片段在做类似的事情。我将代码放在onCreateView中设置服务,并在onPause()和onResume中进行了注册和注销。对我有用。

答案 2 :(得分:0)

可以在service_init()中检查修改寄存器接收器吗  

getActivity().registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());

以及取消注册的接收者

getActivity().unregisterReceiver(UARTStatusChangeReceiver);