2011-03-21 18 views

回答

178

是,与投:

((Activity) ctx).finish(); 
+2

只有当前活动,否则非当前活动将完成:) – ernazm 2011-03-21 11:08:47

+2

这可能会导致问题,如果'Context'实际上是一个应用程序上下文。 – user634618 2011-03-21 11:24:41

+1

如果上下文是应用程序上下文,该如何实现。我正在类中运行一个计时器线程,如果时间结束,我想关闭该类中的当前活动。 – Sando 2011-09-12 08:58:36

1

如果您有机会获得你想要完成活动的运行视图(例如,你在点击监听器),你可以这样做:

((Activity)getContext()).finish(); 

(与感谢2red13让我在这里)。

10

在我的情况下面工作,

我需要完成我的活动中的AsyncTask onPostExcute()。

其中我的AsyncTask类是单独的公共类,它具有带有参数Context的构造函数。

((Activity)(mContext)).finish(); 

只有上述工作对我来说...反正我有这个想法来自@ 2red13和@lucy答案...感谢所有...

+0

这在现在是不同的形式'((Activity)mContext).finish()'。 – prakharsingh95 2015-06-16 11:23:59

-1

尝试:

((Activity) context.getApplicationContext()).finish(); 
+4

请勿使用此“解决方案”!你不能猜测(你可能总是错),你的应用程序上下文与你的Activity相同。 – marciowb 2014-02-11 22:55:47

8

我知道这是一个老的文章,但,也许它可能是一个好主意,这样调用它:

if(context instanceof Activity){ 
       ((Activity)context).finish(); } 

这样,我们要确保我们没有得到任何ü nnecesary ClassCastExceptions异常

1

如果您在使用启动活动:

startActivityForResult(i, 1); 

你可以调用finishActivity(1)完成的任何活动开始与该请求的代码,像这样:

((Activity)getContext()).finishActivity(1); 

在我的案例我需要在处理程序postDelayed中使用一个。使用这个你可以确定你正在完成哪些活动。希望能帮助到你!

0

我在关闭首选项活动时遇到同样的问题。下面是我做的:

public class T2DPreferenceActivity extends PreferenceActivity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
      getFragmentManager().beginTransaction().replace(android.R.id.content, 
       new T2DPreferenceFragment()).commit(); 
    } 

    public static class T2DPreferenceFragment extends PreferenceFragment { 
     @Override 
     public void onCreate(final Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      addPreferencesFromResource(R.xml.server_screen_preference); 
      Preference testServicePreference = getPreferenceScreen().findPreference("PREFERRED SERVER"); 
      testServicePreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { 
       @Override 
       public boolean onPreferenceChange(Preference preference, Object newValue) { 
        T2DPreferenceActivity.closeActivity(getActivity()); 
        return true; //returning true still makes the activity handle the change to preferences 
       } 
      }); 
     } 

     public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 
      super.onViewCreated(view, savedInstanceState); 
      ListView lv = (ListView)view.findViewById(android.R.id.list); 
      ViewGroup parent = (ViewGroup)lv.getParent(); 
      parent.setPadding(0, 100, 0, 0); 
     } 
    } 

    protected static void closeActivity(Activity activity) { 
     activity.finish(); 
    } 
} 
相关问题