简体   繁体   中英

Xamarin Android passing data

I currently have a service running in the background to access location properties such as latitude and longitude. Every time the service OnLocationChange hits, i send the data into a broadcast receiver. The broadcast receiver class waits and receives the latitude and longitude and stores them nicely as doubles.

I now want to access the two doubles from the broadcast receiver class. I've tried Get and Set methods but the data always passes through as null or 0.

This is my default Receiver class without any get set methods implemetned:

[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { "GpsReceiever" })]
public class GPSReceiver : BroadcastReceiver
{
    public double latData;
    public double longData;
    public double altData;
    public float accData;

    public override void OnReceive(Context context, Intent intent)
    {
        latData = intent.Extras.GetDouble("lat");
        longData = intent.Extras.GetDouble("long");
        altData = intent.Extras.GetDouble("alt");
        accData = intent.Extras.GetFloat("acc");
    }
}

Am i able to pass the data through to another class? and if so how would i go about it?

Thank you for your time!

There are a couple of options.

  • Register receiver on Context, eg activity or service, and pass class in the constructor that should receive notifications register receiver
  • Have them as a static variables (not a very elegant solution) either on receiver or some sort of singleton class that would represent your data
  • If you want to notify a service and you expect it to be running or want to start it you can call startService with appropriate extras and read them in onStartCommand. Note you can do similar trick with activity but you have to change launch mode which probably is not desired.

Please also read: Broadcast receiver's life cycle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM