java - 使用上下文从自定义 View 完成 Activity

标签 java android eclipse

这是我的代码:

    private void makeDialog2() {
    AlertDialog.Builder about = new AlertDialog.Builder(getContext());
    about.setTitle("You Won!");

    about.setPositiveButton("Play Again",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    Intent playIntent2 = new Intent(getContext(),
                            PracticePlayActivity.class);
                    playIntent2.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    getContext().startActivity(playIntent2);
                    ((Activity) getContext()).finish();
                }
            });

    about.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface arg1, int arg2) {
            Intent playIntent = new Intent(getContext(),
                    PlayChooserActivity.class);
            playIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            getContext().startActivity(playIntent);
            ((Activity) getContext()).finish();
        }
    });

    about.show();
}

当用户输了游戏想重试时会提示这段代码。但是,当我按重试 4 次以上时,应用程序崩溃了。我怀疑内存泄漏。在 logcat 中进行一些测试后,我设法发现该 Activity 在重试后仍在运行。

我的计划是用两件事来解决这个问题。回收我的可绘制对象并结束整个第一个 Activity 。但是,即使在我调用 finish 之后,第一个 Activity 也没有关闭。有什么帮助吗? (到目前为止,在我的代码的其他部分使用 getContext() 一直有效)。

编辑:通过结束 Activity 它会自动销毁变量吗?还是我还需要清除 Android 内存中的位图?我有什么想法可以做到这一点吗?

最佳答案

如果 makeDialog2() 是在 Activity 中声明的,请尝试使用 thisYourActivityName.this 而不是 getContext()。如果不是,则尝试使用 thisYourActivityName.this 从您调用该方法的地方将 Context 作为参数传递给该方法。

By ending the activity does it destroy the variables automatically?

完成 Activity 应该销毁它和所有相关资源。如果稍后启动 Activity 的新实例,它将重新创建其所有资源。除非您使用某种静态变量 - 只要您的应用程序正在运行,它们就会保持“Activity 状态”。


The place where this method is being called from is actually the surfaceview therefore any parameter i give it will essentially still be getContext(). Is there any way around this? I don't see why ((Activity) getContext()).finish(); isn't working

看看 documentation for the Activity-class .

如您所见,ContextActivity 的父类(super class) - 这意味着每个 Activity 都是一个 Context 但是并非每个 Context 都是 Activity。换句话说,((Activity) getContext()).finish(); 可能会导致 ClassCastException

要验证您获得的 Context 实际上也是一个 Activity,您可以做如下检查:

if( getContext() instanceof Activity )
   Log.e( "TAG", "getContext() returns an Activity!" );

在您调用 finish() 之前添加它并检查 LogCat 是否同意它是一个 Activity

关于java - 使用上下文从自定义 View 完成 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8586818/

相关文章:

JavaParser:构造函数 ParseException(字符串)未定义

java - 如何创建 Apache cxf 简单 Web 服务使用者?

android - 在Android中将布局 View 的背景颜色设置为渐变?

android - 自定义 View 只显示一次

java - 如何在Android中获取应用程序数据目录

java - 获取 Activity UI 的 "Session Expired"消息

Java:为什么打包成jar文件的代码会阻止外部类访问?

android - 创建新项目时没有构建目标

android - 我想在 eclipse 中打开 acra 项目

android - 如何在浏览器中控制 cordova 应用程序