• 5
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Broadcast manager not working in Fragment

I have a BroadcastReceiver which is used to receive data from a BLE device. The same code is working fine in an Activity but not in Fragment.

Here is the code:

    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;

    }

The complete code in the same ay with a few changes in working fine in Activity. Any idea what might be the blocker.? Do I need to do something else in the fragment to receive the data from the Local Broadcast Manager.?

    • When your using LocalBroadcastManager it can only for app level but your trying to listen system lever broadcast use getActivity().registerReceiver()

Please try this way : Create class 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();
        }
    }
}

And in your 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;

            }
        }
    }
}

And to send your broadcast this this code :

BroadcastHelper.sendInform(context, "Test");

Or if you want to send data with it use :

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

I have a fragment where I do something similar. I put my code to setup the service in onCreateView and have a register and unregister in onPause() and onResume. Works good for me.

  • 0
Reply Report

Can you check modify register receiver in service_init() as

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

and for unregisterer receiver

getActivity().unregisterReceiver(UARTStatusChangeReceiver);
  • 0
Reply Report