android - 在 Toast .maketext() 方法中使用 getApplicationcontext() 和 this 有什么区别

标签 android android-context

是否有我必须在 Toast.makeText() 方法的上下文参数中使用 getApplicationcontext() 或 this 的特定实例

 Toast.makeText(this, "HI", Toast.LENGTH_LONG).show();

 Toast.makeText(getApplicationcontext(), "HI", Toast.LENGTH_LONG).show();

最佳答案

getApplicationContext:

根据 Developer documention : getApplicationContext

返回当前进程的单个全局 Application 对象的上下文。这通常只应在您需要一个生命周期与当前上下文分离的上下文时使用,该上下文与进程的生命周期而不是当前组件相关联。

使用:

借助获取应用程序上下文的帮助,您可以在整个应用程序中使用

public class YourApp extends Application
{
 static YourApp appstate;
 public void onCreate(Bundle savedInstanceState){
    super.onCreate();
    appstate = this;
   }
 public static YourApp getApplication(){
    return appstate;
   }
}

如何使用:YourApp.getApplication();


这个

在实例方法或构造函数中,这是对当前对象的引用。

使用:只要你能看到你的Activity Context,你就可以使用

例如

public void onCreate(Bundled savedInstanceState)
{
 ...
Toast.makeText(this, "HI", Toast.LENGTH_LONG).show();
}

如何使用 Toast.makeText() 区分 thisgetApplicationContext() 的使用?

尝试将 AynscTask 中的 Toast.makeText() 与 thisgetApplicationContext 一起使用。

关于android - 在 Toast .maketext() 方法中使用 getApplicationcontext() 和 this 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23707982/

相关文章:

java - 后台服务上的 Android getContext

android - 如何在 Singleton 和 SharedPreferences 类中传递应用程序上下文

java - 传入 BroadcastReceiver 的 onReceive() 的 Context 是什么?

安卓NDK : how to make the command "ndk-gdb --help" work in console?

android - 争论这行不通。 [需要 : 'android.content.context'

android - 带光标的 ListActivity

android - 试图将按钮移动到屏幕的右侧。我的权利不是电脑的权利

android - 我真的需要将 Context 实例深入到应用程序中吗?

android - Flutter 如何在没有任何用户交互的情况下从一个页面导航到另一个页面

android - Android 网络位置提供商的准确度和速度有多快?