我的应用程序中有一个服务,我可以访问包含我需要的内容的 strings.xml 文件。
我想获取 strings.xml 中的字符串,但我无法在我的服务中访问该文件。
我认为问题涉及上下文,但我无法解决它。
有一段我的服务摘录:
package com.receiver;
protected Void doInBackground() {
// GPS timeout
final int maxSeconds = 60; //30
int count = 0;
// If we've finished finding location or exceeded timeout,
// break the loop.
while (findingLocation && count < maxSeconds) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Continue if interrupted
}
// Increment the timer by one second
count++;
}
// If we're still finding location, switch to network locations.
if (findingLocation) {
locationHandler.sendMessage(new Message());
locationManager.removeUpdates(SMSReceiver.this);
lat = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLatitude();
lng = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLongitude();
msg = "";// here I whant to get my string from the strings.xml but I can't access to this file
} else {
lat = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude();
lng = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude();
msg = " "; // here I whant to get other string from the strings.xml but I can't access to this file
}
感谢您的帮助。
抱歉我的英语不好。
最佳答案
您是否正在使用 Android 服务?从您的代码 fragment 来看,您似乎想要从 AsyncTask 访问字符串。
对于常规的 Android 服务,您可以使用 Context
中的 getString()
方法,因为 Service
扩展了 Context
。只需传入所需字符串的资源 ID,即可完成所有设置。
http://developer.android.com/reference/android/content/Context.html#getString(int )
为了从 AsyncTask
访问字符串,我通常只需将 ApplicationContext 传递给 AsyncTask
,然后我就可以访问任何我想要的内容。请记住,传递上下文可能会有问题,因此您可能希望将实际字符串传递给 AsyncTask
,这样它就不需要 Context
引用。
关于android - 如何在服务中使用 strings.xml 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9650688/