如何获得当前的前台活动的上下文中的android? [英] How to get current foreground activity context in android?
问题描述
每当执行我广播我想告诉警惕前台活动。
Whenever my broadcast is executed I want to show alert to foreground activity.
推荐答案
(注意:一个官方的API中添加了API 14:看到这个答案<一个href="http://stackoverflow.com/a/29786451/119733">http://stackoverflow.com/a/29786451/119733)
(Note: An official API was added in API 14: See this answer http://stackoverflow.com/a/29786451/119733)
不要使用preVIOUS(waqas716)的答案。
DO NOT USE PREVIOUS (waqas716) answer.
您将有因为静态引用到活动的内存泄漏问题。欲了解更多详细信息请访问以下链接<一个href="http://android-developers.blogspot.fr/2009/01/avoiding-memory-leaks.html">http://android-developers.blogspot.fr/2009/01/avoiding-memory-leaks.html
You will have memory leak problem, because of the static reference to the activity. For more detail see the following link http://android-developers.blogspot.fr/2009/01/avoiding-memory-leaks.html
要避免这种情况,你应该管理活动的参考。 添加应用程序的名称清单文件中:
To avoid this, you should manage activities references. Add the name of the application in the manifest file:
<application
android:name=".MyApp"
....
</application>
您的应用程序类:
public class MyApp extends Application {
public void onCreate() {
super.onCreate();
}
private Activity mCurrentActivity = null;
public Activity getCurrentActivity(){
return mCurrentActivity;
}
public void setCurrentActivity(Activity mCurrentActivity){
this.mCurrentActivity = mCurrentActivity;
}
}
创建一个新的活动:
Create a new Activity :
public class MyBaseActivity extends Activity {
protected MyApp mMyApp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMyApp = (MyApp)this.getApplicationContext();
}
protected void onResume() {
super.onResume();
mMyApp.setCurrentActivity(this);
}
protected void onPause() {
clearReferences();
super.onPause();
}
protected void onDestroy() {
clearReferences();
super.onDestroy();
}
private void clearReferences(){
Activity currActivity = mMyApp.getCurrentActivity();
if (this.equals(currActivity))
mMyApp.setCurrentActivity(null);
}
}
所以,现在,而不是为你的活动扩展Activity类,只是扩展MyBaseActivity。现在,你可以从应用程序或活动的情况下一样,让你的当前活动:
So, now instead of extending Activity class for your activities, just extend MyBaseActivity. Now, you can get your current activity from application or Activity context like that :
Activity currentActivity = ((MyApp)context.getApplicationContext()).getCurrentActivity();
这篇关于如何获得当前的前台活动的上下文中的android?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!