Как я могу использовать getSystemService в классе non-activity (LocationManager)?
У меня возникли проблемы с загрузкой задач из основного метода Activity OnCreate в другой класс, чтобы сделать тяжелый подъем.
Когда я пытаюсь вызвать getSystemService из класса non-Activity, генерируется исключение.
Любая помощь будет принята с благодарностью:)
lmt.java:
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();
Location location = lfyl.getLocation();
String latLongString = lfyl.updateWithNewLocation(location);
TextView myLocationText = (TextView)findViewById(R.id.myLocationText);
myLocationText.setText("Your current position is:\n" + latLongString);
}
}
fyl.java
package com.atClass.lmt;
import android.app.Activity;
import android.os.Bundle;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.content.Context;
public class fyl {
public Location getLocation(){
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
return location;
}
public String updateWithNewLocation(Location location) {
String latLongString;
if (location != null){
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
}else{
latLongString = "No Location";
}
return latLongString;
}
}
Ответы
Ответ 1
Вам нужно передать свой контекст в свой класс fyl.
Одно из решений делает такой конструктор для вашего класса fyl
:
public class fyl {
Context mContext;
public fyl(Context mContext) {
this.mContext = mContext;
}
public Location getLocation() {
--
locationManager = (LocationManager)mContext.getSystemService(context);
--
}
}
Итак, в вашем классе активности создайте объект функции fyl в onCreate
следующим образом:
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);
}
}
Ответ 2
Вы можете пойти на это:
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
Ответ 3
Один из способов, с которым я столкнулся, - создать статический класс для экземпляров. Я много использовал в AS3. Я отлично поработал у меня в разработке Android.
Config.java
public final class Config {
public static MyApp context = null;
}
MyApp.java
public class MyApp extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Config.context = this;
}
...
}
Затем вы можете получить доступ к контексту или с помощью Config.context
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = Config.context.getSystemService(context);
Ответ 4
Я не знаю, поможет ли это, но я сделал это:
LocationManager locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
Ответ 5
(LocationManager) ((lmt) new Activity()).getSystemService(context);
Попробуйте этот код. Это будет работать, только если вы запустили работу, прежде чем вызывать эту строку кода. Поскольку действие должно создаваться и выполняться.