Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 58056

How can I use the context from a started service

$
0
0

Hello,

I started a service which listens to GCM messages. When a message is received a class will be called. In this class I want to use the WifiManager, but the wifimanager needs the Context. But because the class is not an Activity I cannot get the Context.

Here is my code:
[Service]
public class PushHandlerService : GcmServiceBase
{
public PushHandlerService() : base(GcmBroadcastReceiver.SENDER_IDS) { }
protected override void OnMessage (Context context, Intent intent)
{
Log.Info(TAG, "GCM Message Received!");

        var msg = new StringBuilder();

        if (intent != null && intent.Extras != null)
        {
            foreach (var key in intent.Extras.KeySet())
                msg.AppendLine(key + "=" + intent.Extras.Get(key).ToString());
        }

        var prefs = GetSharedPreferences(context.PackageName, FileCreationMode.Private);
        var edit = prefs.Edit();
        edit.PutString("last_msg", msg.ToString());
        edit.Commit();

        string command = intent.GetStringExtra ("command");
        createNotification("GCM Sample", "Message Received for GCM Sample... Tap to View!");
        if (command != null && command.Equals ("determine_location")) {
            LocationRetriever locationRetriever = new LocationRetriever ();
            locationRetriever.CheckLocation ();
        }

    }

}

public class LocationRetriever : Java.Lang.Object,ILocationRetriever, ILocationListener
{
private static WifiManager wifi;
private WifiReceiver wifiReceiver;

public LocationRetriever() {

        wifi = (WifiManager)Config.context.GetSystemService(Context.WifiService);
        wifiReceiver = new WifiReceiver(this);
        Config.context.RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.ScanResultsAvailableAction));
    }

}


Viewing all articles
Browse latest Browse all 58056

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>