Проблема следующая: при переходе выполнения к строке с locationManager вылетает исключение FATAL EXCEPTION: main.
Подробнее: В MainActivity вызываю конструктор GPSTracker(MainActivityCW.this), после чего, при наличии не закоментированного try в классе GPSTracker, получаю исключение FATAL EXCEPTION: main. Соответственно tracker.canGetLocation() в MainActivityCW получает значение false (значение по умолчанию). Пробовал убирать, перемещать строку с locationManager, но везде именно на ней ошибка.
Код GPSTracker:
import...
public class GPSTracker implements LocationListener {
private final Context mContext;
// flag for GPS status
public boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
Log.i("GPS", "CONSTRUCTOR");
getLocation();
}
// Function to get the user's current location
public Location getLocation() {
Log.i("GPS", "getLocation method");
//try {
Log.i("GPS", "try 1");
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
Log.i("GPS", "try 2");
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.i("GPS", "isGPSEnabled =" + isGPSEnabled);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.i("GPS", "isNetworkEnabled =" + isNetworkEnabled);
if (isGPSEnabled == false && isNetworkEnabled == false) {
// no network provider is enabled
Log.i("GPS","no network provider is enabled");
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
location=null;
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.i("GPS", "Network Enabled!");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
location=null;
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
//} catch (Exception e) {
// Log.i("GPS", "getLocation EXCEPTION");
// e.printStackTrace();
//}
return location;
}
//Stop using GPS listener Calling this function will stop using GPS in your app
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
// Function to get latitude
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
// Function to get longitude
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
// Function to check GPS/wifi enabled
public boolean canGetLocation() {
Log.i("GPS","canGetLocation method");
return this.canGetLocation;
}
// Function to show settings alert dialog On pressing Settings button will launch Settings Options
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Код MainActivity:
public class MainActivityCW extends Activity {
TextView currentCoordinates;
GPSTracker tracker = new GPSTracker(MainActivityCW.this);
double latitude;
double longitude;
Timer timer = new Timer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
currentCoordinates = (TextView) findViewById(R.id.currentCoordinates);
final long UPD_START_DELAY = 0; // 1 сек = 1000 мс
final long UPD_PERIOD = 5000; // 1 сек = 1000 мс
timer.schedule(new UpdateCoordinates(), UPD_START_DELAY, UPD_PERIOD);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
public void goToSettings(View v) {
Intent relationMainToSettings = new Intent(this, Settings.class);
startActivity(relationMainToSettings);
}
class UpdateCoordinates extends TimerTask {
@Override
public void run() {
MainActivityCW.this.runOnUiThread(new Runnable() {
public void run() {
try {
latitude = tracker.getLatitude();
longitude = tracker.getLongitude();
currentCoordinates.setText("Lat: " + Double.toString(latitude) + " Lon: "
+ Double.toString(longitude));
} catch (Exception e) {
e.fillInStackTrace();
}
}
});
}
}
}
Ошибка:
11-20 01:25:01.373 9258-9258/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{ua.repikserj.CarpatianWays/ua.repikserj.CarpatianWays.MainActivityCW}: java.lang.IllegalStateException: System services not available to Activities before onCreate()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2001)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
at android.app.ActivityThread.access$600(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4624)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:965)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:732)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate()
at android.app.Activity.getSystemService(Activity.java:4033)
at ua.repikserj.CarpatianWays.GPSTracker.getLocation(GPSTracker.java:51)
at ua.repikserj.CarpatianWays.GPSTracker.<init>(GPSTracker.java:42)
at ua.repikserj.CarpatianWays.MainActivityCW.<init>(MainActivityCW.java:17)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1992) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104) at android.app.ActivityThread.access$600(ActivityThread.java:134) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:4624) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:965) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:732) at dalvik.system.NativeStart.main(Native Method)