访问Service中的共享首选项

时间:2016-12-02 06:42:57

标签: service locationlistener android-sharedpreferences

我正在开发一种服务,它将捕获实现LocationListener的经度和纬度。

此外,我尝试在捕获时更新共享首选项中的经度和纬度值。

但是,我在服务中使用sharedpreference时遇到运行时错误。我认为问题在于背景。我试过,getApplicationContext(),getBaseContext()但没有工作。

public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
//  private GPSTrackerImplementation mCallback;
// flag for GPS status
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 = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;

//public SharedPrefference shareObj;

String address;
String city;
String state;
String country;
String postalCode;
String knownName;
Geocoder geocoder;
List<Address> addresses;

public SharedPrefference shareObj;


public GPSTracker(Context context) {

    this.mContext = context;
   // PreferenceManager.getDefaultSharedPreferences(context);
   // SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    try {
        locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
        // getting network status
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        // getting GPS status
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

       if (!isGPSEnabled && !isNetworkEnabled) {
           //PreferenceManager.getDefaultSharedPreferences(context).edit().putString("GPS_ENABLED", "Y").commit();

       // if (!isGPSEnabled) {
            // no network provider is enabled
        } else this.canGetLocation = true;
        // First get location from Network Provider
        if (isNetworkEnabled) {

            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            Log.d("Network", "Network");
            getLocation();
        }

        if (isGPSEnabled) {
            if (location == null) {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            Log.d("GPS", "GPS");
            getLocation();

            }
        }

    }catch (SecurityException e) {
        e.printStackTrace();
    }


    getLocation();
}

public Location getLocation() {
    try {


                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        //location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {

                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            Log.d("On constructor-GPS", "latitude"+latitude);
                            Log.d("On constructor-GPS", "longitude"+longitude);
                            return location;
                        }
                        else {

                            return locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        }
                    }

                }catch (SecurityException e) {
                    e.printStackTrace();
                }

    return location;
}



/**
 * 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
 *
 * @return boolean
 */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 */


@Override
public void onLocationChanged(Location location) {
    this.location = location;
    latitude = location.getLatitude();
        longitude = location.getLongitude();
//        Toast.makeText(this, "location changed", Toast.LENGTH_LONG).show();
        Log.d("n location changed", "latitude"+latitude);
        Log.d("On location changed", "longitude"+longitude);
        String m_latStr = Double.toString(latitude);
        String m_longStr = Double.toString(longitude);
        PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString("LATITUDE", m_latStr).commit();
        PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString("LONGITUDE", m_longStr).commit();

}

logcat的

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
                                                                           at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:375)
                                                                           at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:370)
                                                                           at com.teamlease.gps.services.GPSTracker.onLocationChanged(GPSTracker.java:195)
                                                                           at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:285)
                                                                           at android.location.LocationManager$ListenerTransport.-wrap0(LocationManager.java)
                                                                           at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:230)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:148)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

0 个答案:

没有答案