【问题标题】:Getting the context in a Thread called by a Service在服务调用的线程中获取上下文
【发布时间】:2011-10-21 11:40:35
【问题描述】:

我有以下代码:

public class DumpLocationLog extends Thread {
    LocationManager lm;
    LocationHelper loc;
    public void onCreate() {
        loc = new LocationHelper();
        lm = (LocationManager) Context.getSystemService(Context.LOCATION_SERVICE);
    }
    public void run() {
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, loc);
    }
}

我希望它从远程服务运行,但在 lm = (LocationManager) Context.getSystemService(Context.LOCATION_SERVICE); 行中我当然会收到 NullPointerException 错误,因为 context 为空。

我怎样才能在这里获得上下文? getBaseContext()getApplicationContext() 不起作用。

【问题讨论】:

    标签: android multithreading service location android-context


    【解决方案1】:

    默认情况下,Thread 不能直接访问 Context;你必须把它传递进去。线程也不需要onCreate 方法(我猜你是手动调用的)——我只是将它更改为构造函数。您可以在 Thread 的构造函数中传入一个 Context:

    public class DumpLocationLog extends Thread {
        LocationManager lm;
        LocationHelper loc;
        public DumpLocationLog(Context context) {
            loc = new LocationHelper();
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        }
        public void run() {
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, loc);
        }
    }
    

    如果在 Service 内部使用,您可以使用 new DumpLocationLog(this); 实例化它(Service 是 Context 的子类,因此 this 在这里工作)。通过调用start() 方法启动线程。

    【讨论】:

    • 我就是这样,从new DumpLocationLog().start(); 之类的服务调用虽然我已经尝试过使用new DumpLocationLog(getApplicationContext()).start();new DumpLocationLog(getBaseContext()).start();,但它们都不起作用。
    • 这是我尝试和工作的! Content context;new DumpLocationLog(context, latString, lngString).start();
    【解决方案2】:

    您可以通过构造函数传递一个有效的上下文,或者,如果您的类是服务内的内部类,您可以使用 ServiceClassName.this.getContext()

    【讨论】:

    • 我尝试通过构造函数传递有效上下文,但随后出现异常Can’t create handler inside thread that has not called Looper prepare in Android。我的班级不是内部班级,我可以将其设为内部班级吗?不确定这个..
    猜你喜欢
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    相关资源
    最近更新 更多