不要使用上一个(waqas716)的答案。
为避免这种情况,您应该管理活动参考。在清单文件中添加应用程序的名称:
android:name=".MyApp"
....
你的申请类: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;
}
}
创建一个新活动: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。现在,您可以从应用程序或活动上下文中获取当前活动:Activity currentActivity = ((MyApp)context.getApplicationContext()).getCurrentActivity();