14

我正在使用 Facebook Android SDK 并希望在用户登录并获取用户对象后关闭我的活动。在实践中,我存储了其中的一部分,但无论如何我都想关闭活动。

      // make request to the /me API
      Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

        // callback after Graph API response with user object
        @Override
        public void onCompleted(GraphUser user, Response response) {
          if (user != null) {
           finish(); // causes errors
          }
        }
      });

IDE错误消息finish()是:"Cannot make a static reference to the non-static method finish() from the type Activity"

如何进行?

4

2 回答 2

31

在 onCreate 中创建对您的活动的引用

//onCreate
final Activity activity = this;

然后你可以在你的 onCompleted 回调中使用它

activity.finish();

你可能不得不Activity activity全球化。

2014 年 2 月 26 日编辑:

请注意,finish()从静态方法调用可能是不好的做法。您正在告诉具有自己生命周期的特定实例Activity,它应该从静态方法中自行关闭,没有任何生命周期或状态。理想情况下,您会finish()从绑定到Activity.

于 2013-05-06T16:19:51.503 回答
5

对于某些人来说,bclymer 的方法可能行不通。它没有在我的,使用最新的 beta 版本 Android Studio ......试试这个......

public class myActivity extends Activity {

    public static Activity activity = null;
    ...
    ...

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myActivity_layout);

        activity = this;
        ....
        ....
    }
}

从您在同一个包中的其他活动中,只需....

    // use try catch to avoid errors/warning that may affect the 
    // next method execution
    try {
         myActivity.activity.finish();
    } catch (Exception ignored) {}
于 2014-11-17T08:26:37.597 回答