跟踪用户关闭/启动应用程序

时间:2016-03-30 19:11:21

标签: android mongodb android-asynctask android-lifecycle activity-lifecycle

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

到目前为止我所尝试的是:在我的应用程序的每个活动中,我都称之为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);

我认为这应该可以正常工作并使用用户在线/离线情况更新我的文档,但事实并非如此。我想知道这是因为当应用程序处于后台时AsyncTask无法正常工作,或者我做错了什么。无论如何,我们非常感谢任何帮助。

修改

  

AsyncTask中的Log.d()表示y但不是x。 AsyncTask正在为onCreate()方法执行,但对于onStop()

则不执行

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

1 个答案:

答案 0 :(得分:2)

短版本是&#34; you should avoid performing CPU-intensive work during onPause(), such as writing to a database&#34;。这来自managing the activity lifecycle(建议阅读)。

但是,正如您和其他人所说,暂停和停止应用程序不会停止后台线程。完全关闭应用程序后,将调用onDestroy。这确实会杀死所有东西(顾名思义)。

此外,暂停活动意味着部分隐藏了UI。当警报窗口显示在其上时,可能会发生这种情况。但是,大多数onPause都发生在onStop之前。无论应用程序是否仍在运行,&#34;一旦您的活动停止,系统可能会在需要恢复系统内存时销毁该实例。&#34;

请注意,在onPause期间避免CPU密集的建议不适用于onStop。 Google's example shows writing to storage。它没有在那里指定,但我认为生成后台线程来实现这一点实际上是一个坏主意,因为系统可能会认为一旦onStop存在,活动就准备好了onDestroy。

我的原始推荐仍然有效。如果您在活动上创建Service onDestroy,则不适用于该活动。

相关问题