是否有特定情况下需要在Toast.makeText()方法的上下文参数中使用getApplicationcontext()或this?
Toast.makeText(this, "HI", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationcontext(), "HI", Toast.LENGTH_LONG).show();
是否有特定情况下需要在Toast.makeText()方法的上下文参数中使用getApplicationcontext()或this?
Toast.makeText(this, "HI", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationcontext(), "HI", Toast.LENGTH_LONG).show();
getApplicationContext:
根据开发者文档: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();
this
在实例方法或构造函数中,this是指当前对象的引用。
用法:只要您能看到您的Activity Context,就可以使用它
例如:
public void onCreate(Bundled savedInstanceState)
{
...
Toast.makeText(this, "HI", Toast.LENGTH_LONG).show();
}
如何区分在使用Toast.makeText()
时this
和getApplicationContext()
的不同?
尝试在AynscTask
中使用this
和getApplicationContext()
来调用Toast.makeText()
。
View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity.
Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.
“this”和getContext()是相同的。
[参考] [getContext(),getApplicationContext(),getBaseContext()和“this”的区别]1