Search code examples
javaandroidandroid-intentandroid-broadcast

Intent not being registered through Broadcast Listener


I have been trying for a long time to figure out how to send data from the service class to the mainactivity class. I am using broadcast receivers right now to do it. The issue is that they aren't being received in the MainActivity class.

public class MyService extends Service {
    //all my code for the service which takes the users gps location.
    private static final String TAG = "Hello";
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 10;//change this for time
    private static final float LOCATION_DISTANCE = 0f;//change this to get it every distance
    private static final String MY_ACTION = "MY_ACTION";
    private final Handler handler = new Handler();
    Intent intent;
    private class LocationListener implements android.location.LocationListener {
        Location mLastLocation;

        public LocationListener(String provider) {
            //Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location location) {
            //Log.e(TAG, "onLocationChanged: " + location.toString());
            mLastLocation.set(location);

        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.e(TAG, "onProviderDisabled: " + provider);
        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.e(TAG, "onProviderEnabled: " + provider);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }
    //different possible uses for locations
    LocationListener[] mLocationListeners = new LocationListener[]{
            new LocationListener(LocationManager.GPS_PROVIDER),
            new LocationListener(LocationManager.NETWORK_PROVIDER)
    };

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
    //the start of the activity sends data every 5 seconds
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);
        handler.removeCallbacks(sendUpdatesToUI);
        handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate");
        //initializes locationManager
        initializeLocationManager();      
        try {
            Toast.makeText(MyService.this, "It Works", Toast.LENGTH_SHORT).show();
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[0]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "gps provider does not exist " + ex.getMessage());
        }
    }

    private void initializeLocationManager() {
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }
    private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            DisplayLoggingInfo();
            handler.postDelayed(this, 5000); // 5 seconds delay
        }
    };

    private void DisplayLoggingInfo() {
        Log.d(TAG, "entered DisplayLoggingInfo");
        intent = new Intent();
        initializeLocationManager();
        try {
            Toast.makeText(MyService.this, "It Works", Toast.LENGTH_SHORT).show();
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[0]);
            intent.putExtra("Latitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude());
            intent.putExtra("Longitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude());
            sendBroadcast(intent);
            Log.i(TAG,"intent sent");
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "gps provider does not exist " + ex.getMessage());
        }
    }
}

The data is sent. When I try to access it from MainActivity, though, it doesn't seem to get it.

public class MainActivity extends AppCompatActivity {
        public SimpleLocation location;
        Intent intent;
        double latitude;
        double longitude;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            //Sets views for Android
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);  
            startService(new Intent(this, MyService.class));
            intent = new Intent(this, MyService.class);
            LocalBroadcastManager.getInstance(this).registerReceiver(
                    broadcastReceiver, new IntentFilter());
            Toast.makeText(MainActivity.this, "" + latitude, Toast.LENGTH_SHORT).show();
        }    

//sets up broadcast Reciever
        private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Double latitude = intent.getDoubleExtra("Latitude", 0);
                Double longitude = intent.getDoubleExtra("Longitude", 0);
                Log.d("hello", "It came this far");
                Log.d("hello", "         " + latitude);
                Log.d("hello", "       " + longitude);
                TextView txtDateTime = (TextView) findViewById(R.id.textView);
                txtDateTime.setText(latitude.toString());
            }
        };

        @Override
        public void onResume() {
            super.onResume();
            startService(intent);
            registerReceiver(broadcastReceiver, new IntentFilter());
        }

        @Override
        public void onPause() {
            super.onPause();
            unregisterReceiver(broadcastReceiver);
            stopService(intent);
        }

    }

Does anyone know what I am doing wrong?


Solution

  • First,you should add an action to your intent be sent,assume is location,then replace

     intent.putExtra("Latitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude());
     intent.putExtra("Longitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude());
     sendBroadcast(intent);
    

    with

     intent.setAction("location");
     intent.putExtra("Latitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude());
     intent.putExtra("Longitude", mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude());
     LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    

    And replace

    LocalBroadcastManager.getInstance(this).registerReceiver(
                    broadcastReceiver, new IntentFilter());
    

    with

    IntentFilter filter = new IntentFilter("location");
    LocalBroadcastManager.getInstance(this).registerReceiver(
                    broadcastReceiver, filter);
    

    And you should register receiver before start service,so replace

        @Override
        public void onResume() {
            super.onResume();
            startService(intent);
            registerReceiver(broadcastReceiver, new IntentFilter());
        }
    

    with

        @Override
        public void onResume() {
            super.onResume();
           LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, new IntentFilter());
            startService(intent);
        }
    

    And since you have register in onResume,so you can remove

    LocalBroadcastManager.getInstance(this).registerReceiver(
                    broadcastReceiver, new IntentFilter());
    

    from your onCreate method.