是否有任何特定的实例我必须在Toast.makeText()方法的上下文参数中使用getApplicationcontext()或this
Toast.makeText(this, "HI", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationcontext(), "HI", Toast.LENGTH_LONG).show();
答案 0 :(得分:2)
getApplicationContext :
根据Developer documention : getApplicationContext
Return the context of the single, global Application object of the current process. This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component.
使用:
You can use throughout your application with the help of getting Application context using
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();
的此强> 的
Within an instance method or a constructor, this is a reference to the current object.
使用:You can use as along as you can see your Activity Context
e.g。
public void onCreate(Bundled savedInstanceState)
{
...
Toast.makeText(this, "HI", Toast.LENGTH_LONG).show();
}
如何使用this
来区分getApplicationContext()
和Toast.makeText()
的使用?
尝试使用AynscTask
和this
在getApplicationContext
中使用Toast.makeText()。
答案 1 :(得分:2)
您可以关注
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.
"这"和getContext()都是相同的
[参考] [getContext(),getApplicationContext(),getBaseContext()和“this”之间的区别[] 1