Getting the context in a Thread called by a Service

本秂侑毒 提交于 2019-12-22 16:38:07

问题


I have the following piece of code:

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);
    }
}

I want it to be run from a remote service but in the line lm = (LocationManager) Context.getSystemService(Context.LOCATION_SERVICE); I get a NullPointerException error of course, because the context is null.

How can I get the context here? getBaseContext() or getApplicationContext() does not work.


回答1:


A Thread would not have any direct access to a Context by default; you would have to pass it in. A Thread also does not need an onCreate method (which I guess you are calling manually) - I would just change it to a constructor. You can just pass in a Context in the constructor of the Thread:

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);
    }
}

You would instantiate it with new DumpLocationLog(this); if used from inside a Service (a Service is a subclass of Context, so this works here). You start the thread by calling the start() method.




回答2:


You could pass a valid context through the constructor, or, if your class is an inner class inside a service you could use ServiceClassName.this.getContext()



来源:https://stackoverflow.com/questions/6967221/getting-the-context-in-a-thread-called-by-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!