获得了由一种名为线程的上下文 [英] Getting the context in a Thread called by a Service

查看:153
本文介绍了获得了由一种名为线程的上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面这段code的:

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

我希望它是从一个远程服务,但在运行行流明=(的LocationManager)Context.getSystemService(Context.LOCATION_SERVICE); 我收到了 NullPointerException异常当然是错误的,因为背景为null。

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.

我怎么能在这里得到的背景? getBaseContext() getApplicationContext()不起作用。

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

推荐答案

A 不会有一个的任何直接访问上下文默认;你将不得不通过它在一个线程也不需要的onCreate 方法(我猜你是手动调用) - 我只是将其更改为一个构造函数。你可以通过在语境中的Thread的构造函数:

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

如果从服务里使用(服务是;

您将与新DumpLocationLog(本)实例化它语境的一个子类,所以这个在这里工作)。您可以通过调用开始启动线程()方法。

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.

这篇关于获得了由一种名为线程的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆