繁体   English   中英

后台服务上的 Android getContext

[英]Android getContext on a background Service

我正在尝试创建一个即使在我的应用程序关闭时也能运行的服务 但是,我需要在此Service 中使用我的应用程序上下文 当应用程序运行时,服务也能正常工作,但是当我关闭应用程序时(调用了 onDestroy()), getContext()总是返回null

服务

public class SubscribeService extends Service {

    private Context context;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this; //Returns null when service is running on background
        context = MyApp.getContext(); //Also null
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //do stuff using context
    }

我的应用程序

public class MyApp extends Application {

    private static Context context;

    public static Context getContext() {
        return context.getApplicationContext();
    }

    @Override
    public void onCreate() {
        context = getApplicationContext();
        super.onCreate();
    }
}

服务从 Activity onCreate() 开始

startService(new Intent(this, SubscribeService.class));

在这种情况下我应该如何使用上下文

编辑

Onik的帮助下设法让它正常工作。 我只需要调用MyApp.getContext(); 之前super.onCreate(); 像这样:

@Override
public void onCreate() {
    context = MyApp.getContext();
    super.onCreate();
}

服务扩展了Context 您可以使用thisthis是对Service实例的引用。

在下面关于SubscribeService类的以下代码的评论中添加更多详细信息:

@Override
public void onCreate() {
    super.onCreate();
    context = this;
    context = MyApp.getContext();
}

在您的ServiceonCreate() context = this ,基本编程范式不能为null

尝试这个:

添加了super.onCreate(); 之前MyApp.context = getApplicationContext();

public class MyApp extends Application {

    private static Context context;

    public void onCreate() {
        super.onCreate();
        MyApp.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return MyApp.context;
    }
}

编辑:调用MyApp.getAppContext()将返回应用程序Context

已经有一次留下了答案,那就是在Service使用getApplicationContext()

此外,在这里使用带有Context.startService(Intent)IntentService可能是有意义的。

...并且在调用super.onCreate()之前不要插入语句。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM