How to Use Getsystemservice in a Non-Activity Class (Locationmanager)

How can I use getSystemService in a non-activity class (LocationManager)?

You need to pass your context to your fyl class..

One solution is make a constructor like this for your fyl class:

public class fyl {
Context mContext;
public fyl(Context mContext) {
this.mContext = mContext;
}

public Location getLocation() {
--
locationManager = (LocationManager)mContext.getSystemService(context);

--
}
}

So in your activity class create the object of fyl in onCreate function like this:

package com.atClass.lmt;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.location.Location;

public class lmt extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

fyl lfyl = new fyl(this); //Here the context is passing

Location location = lfyl.getLocation();
String latLongString = lfyl.updateWithNewLocation(location);

TextView myLocationText = (TextView)findViewById(R.id.myLocationText);
myLocationText.setText("Your current position is:\n" + latLongString);
}
}

android: getSystemService calling from a non extended activity class not working

getSystemService() is a method on Context. You need to have a Context to obtain a system service. Your Activity, for example, is a Context, as the Activity class inherits from Context.

is it posible to use locationManager in a non-activity class

I suspect that your question is if you can get LocationService in non-activity class.
If so, then read below.

To access system services you need to call this method. Activity extends Context, so it's able to get system services. IntentService also extends Context, so you can use your constructor param to get location service.

Error after getSystemService(Context.LOCATION_SERVICE) call

You are trying to use Activity instance that have not created.

Look, you have two Activity: MainActivity and GPSLocation. MainActivity has been started, but GPSLocation not. Inside setLocation method you use instance of GPSLocation activity, but this activity isn't started, onCreate method of this activity wasn't called. To start GPSLocation activty you should call startActivity method. Line GPSLocation(this) is wrong, never create instance of activity itself, always call startActivity method. Also, I think GPSLocation should not extend Activity.


If you need just rid out your crash use this line:

val locationManager = myContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager


Related Topics



Leave a reply



Submit