gpt4 book ai didi

android - 在服务上使用 SharedPreferences 时出现问题(服务上不存在 getPreferences)

转载 作者:IT老高 更新时间:2023-10-28 21:57:35 26 4
gpt4 key购买 nike

我有一些我想从服务访问的共享首选项(纬度、经度),这些首选项不是 Activity 的子类。

特别是,当我尝试访问 getPreferences 时,该功能在服务上不存在。我的代码贴在下面

我的目标是允许在我的服务中写入这些共享首选项。有什么建议/例子可以帮助我吗?

public class MyService extends Service implements Runnable {

LocationManager mLocationManager;
Location mLocation;
MyLocationListener mLocationListener;
Location currentLocation = null;
static SharedPreferences settings;
static SharedPreferences.Editor configEditor;

public IBinder onBind(Intent intent) {
return null;
}

public void onCreate() {
settings = this.getPreferences(MODE_WORLD_WRITEABLE);
configEditor = settings.edit();
writeSignalGPS();
}

private void setCurrentLocation(Location loc) {
currentLocation = loc;
}

private void writeSignalGPS() {
Thread thread = new Thread(this);
thread.start();
}

@Override
public void run() {
mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Looper.prepare();
mLocationListener = new MyLocationListener();
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 0, mLocationListener);
Looper.loop();
//Looper.myLooper().quit();
} else {
Toast.makeText(getBaseContext(),
getResources().getString(R.string.gps_signal_not_found),
Toast.LENGTH_LONG).show();
}
}

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (currentLocation!=null) {
configEditor.putString("mylatitude", ""+currentLocation.getLatitude());
configEditor.putString("mylongitude", ""+currentLocation.getLongitude());
configEditor.commit();
}
}
};

private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
if (loc != null) {
Toast.makeText(getBaseContext(),
getResources().getString(R.string.gps_signal_found),
Toast.LENGTH_LONG).show();
setCurrentLocation(loc);
handler.sendEmptyMessage(0);
}
}

@Override
public void onProviderDisabled(String provider) {}

@Override
public void onProviderEnabled(String provider) {}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}

我在 settings = this.getPreferences(MODE_WORLD_WRITEABLE);

行得到错误

最佳答案

如果您的应用程序只使用一个 SharedPreferences,请让 all 您的代码通过 PreferenceManager.getDefaultSharedPreferences() 获取它.

关于android - 在服务上使用 SharedPreferences 时出现问题(服务上不存在 getPreferences),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4214939/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com