在服务中使用的背景? [英] which context to use in service?

查看:97
本文介绍了在服务中使用的背景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在这种背景下需要作为输入参数的其他类调用的方法,但我有3个可能性服务:

I want to call method in some other class which need Context as input parameter but i have 3 possibility in service:

- getApplicationContext
- getBaseContext
- getApplication

哪一个在 ScreenService 来使用的延伸服务

什么是主要的不同。我读了一些时间前,是不是很好用getApplicationContext。是真的吗?

what is the main different. I read some times ago that is not good to use getApplicationContext. Is that true?

推荐答案

应用程序上下文连接到应用程序的生命周期,并且总是在整个应用程序生命周期相同。所以,如果你使用的是面包,你可以使用应用程序上下文,甚至活动上下文(两者),因为敬酒可以从任何地方提出,在您的应用程序,而不是附加到一个窗口。

Application context is attached to the application's life-cycle and will always be same throughout the life of application. So if you are using Toast, you can use application context or even activity context (both) because a toast can be raised from anywhere with in your application and is not attached to a window.

活动方面连接到活动的生命周期,如果活动的的onDestroy上升可以被摧毁。

Activity context is attached to the Activity's life-cycle and can be destroyed if the activity's onDestroy is raised.

getApplication()虽然它指的是应用程序对象,但应用程序类扩展了Context类,因此它可以用来提供应用程序上下文。

getApplication() though its referring to Application object but the Application class extends Context class, so it can be used to offer application context.

getApplicationContext()提供应用程序上下文。

getApplicationContext() offers application context.

getBaseContext()提供活动场景。

这要看你为什么为此目的正在使用的情况下,

It depends why you for which purpose you are using the context,

getApplicationContext()最preferred的方式,因为这种语境下生活,直到关闭应用程序。

getApplicationContext() is most preferred way since this Context lives untill Application shuts down.

getBaseContext()上下文是提供给小部件和视图。

getBaseContext() Context is available to widgets and Views.

因此​​举杯的消息或创建意图时,他们都有eventhough使用相同的效果 getApplicationContext()才是最正确的。吐司接受,因为它不附加任何形式查看的任何一种语境。它的一个通知。

so in a toast message or when creating an intent, they all have the same effect eventhough using getApplicationContext() is the most correct. Toast accepts any kind of Context since its not attached any kind of View. Its a notification.

这篇关于在服务中使用的背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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