android - 如何在服务中使用 strings.xml 文件?

标签 android service

我的应用程序中有一个服务,我可以访问包含我需要的内容的 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/

相关文章:

javascript - 404 未找到加密值

android - 将数据从 Activity 发送到服务已更新

android - 在 onDestroy() 将变量从服务传输到已经打开的 Main-Activity

c# - Windows Service 需要等待,Thread.Sleep?

android - 当我打开我的项目时,它会出现这个错误非零退出值 126,如何解决这个问题?

android.mk 包含执行命令

Android 模拟器在截屏时一直退出

android - 从数据库 SQLite 中提取更多数据,当在 ListView 中滚动到底部时

android - 有没有办法可以通知应用程序来自设备的指纹已被注销?

java - 清除最近任务时防止杀死服务