Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can not configure Intent and BroadcastReceiver

I want from the "class gps_Listener" create "Intent" and send parameters in "class LocationChangedReceiver"

my class gps_Listener

public class gps_Listener implements LocationListener {

        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            send("I found the location");

        }

        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

        public void send(String str) {
            Intent intent = new Intent("logGPS");
            intent.putExtra("Message", str);
            sendBroadcast(intent);   //-  without context does not work

        }


    }

and class LocationChangedReceiver

public class LocationChangedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

    }

}

I do not know how to do, as you can see there is no "Context"

like image 508
Max Usanin Avatar asked Dec 06 '25 01:12

Max Usanin


1 Answers

You can pass a context to your listener when you create it. So you can use it in your send method:

public class gps_Listener implements LocationListener {
    private Context context;

    public gps_Listener(Context context) {
        this.context = context;
    }

    ...

    public void send(String str) {
        Intent intent = new Intent("com.your.package.YOUR_ACTION");
        intent.putExtra("Message", str);
        context.sendBroadcast(intent);
    }
}

Create it that way:

gps_Listener myListener = new gps_Listener(yourContext);
LocationManager myManager = (LocationManager)getSystemService(LOCATION_SERVICE);
myManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, myListener);

Remember to register your broadcast receiver in the manifest (you could also un/register dynamically):

<receiver android:name=".receivers.LocationChangedReceiver" android:enabled="true">
   <intent-filter>
       <action android:name="com.your.package.YOUR_ACTION"></action>
   </intent-filter>
</receiver>
like image 154
Romain Guidoux Avatar answered Dec 08 '25 16:12

Romain Guidoux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!