在 closing/starting 个应用程序上跟踪用户

Track user on closing/starting application

我正在尝试实施一种方法,我的应用程序将通过更新 mongodb 数据库来跟踪用户何时打开或关闭我的应用程序。 我知道当 activity 启动时 onCreate() 或 onResume() 方法总是启动,当 activity 关闭时 onPause() 或 onStop() 方法正在调用。

到目前为止我尝试过的是:在我的应用程序的每个 activity 中,我都调用这个 AsyncTask:

public void updateOnline(String fbid, boolean login){
    new updateOnlineAsync(fbid, login).execute();
}

public class updateOnlineAsync extends AsyncTask<Void, Void, Void>{
    String fbid;
    boolean login;

    public updateOnlineAsync(String fbid, boolean login){
        this.fbid=fbid;
        this.login=login;
    }


    @Override
    protected Void doInBackground(Void... params) {
        BasicDBObject query = new BasicDBObject();
        query.put("fbid", this.fbid);
        Document myDoc = fb_users.find(query).first();

        if(login){
            Log.d("...", "x");
            Document listItem = new Document("online", "0");
            Document updateQuery = new Document("$set", listItem);
            fb_users.updateOne(myDoc, updateQuery);
        }else{
            Log.d("...", "y");
            Document listItem = new Document("online", "1");
            Document updateQuery = new Document("$set", listItem);
            fb_users.updateOne(myDoc, updateQuery);
        }
        return null;
    }
}

关于 onCreate()、onResume() 我使用的方法:

ServerRequest serverRequest = new ServerRequest(this);
Profile profile = Profile.getCurrentProfile();
serverRequest.updateOnline(profile.getId(), false);

我使用的 onPause()、onStop() 方法:

ServerRequest serverRequest = new ServerRequest(this);
Profile profile = Profile.getCurrentProfile();
serverRequest.updateOnline(profile.getId(), true);

我认为这应该有效,并根据用户 online/offline 的情况更新我的文档,但事实并非如此。我想知道这是不是因为当应用程序在后台时 AsyncTask 不工作或者我做错了什么。无论如何,非常感谢任何帮助。

编辑

Log.d() in AsyncTask ptints y but not x. There for the AsyncTask is executing for onCreate() method but not for onStop()

我刚刚通过更改我的应用程序中的 activity 进行了测试。当我在我的应用程序中更改 activity 或当我按下智能手机的中间按钮(将其发送到后台)时,在线字段会在我的数据库中更新。该方法仅在我完全关闭它时才起作用

简短版本是“you should avoid performing CPU-intensive work during onPause(), such as writing to a database". This is from managing the activity lifecycle(推荐阅读)。

但是,正如您和其他人所指出的,暂停和停止应用程序不会停止后台线程。当您完全关闭应用程序时,将调用 onDestroy。这确实会杀死一切(顾名思义)。

此外,暂停 activity 意味着 UI 被部分隐藏。当其顶部显示警报 window 时,可能会发生这种情况。然而,大多数情况下 onPause 发生在 onStop 之前。该应用程序是否仍然运行,"Once your activity is stopped, the system might destroy the instance if it needs to recover system memory."

请注意,在 onPause 期间避免 CPU 密集的建议不适用于 onStop。 Google's example shows writing to storage。那里没有指定,但我认为生成后台线程来执行此操作实际上是一个坏主意,因为一旦 onStop 存在,系统可能会假设 activity 已为 onDestroy 做好准备。

我最初的建议仍然有效。如果您创建 Service,activity 上的 onDestroy 将不适用于它。