0

我正在制作一个需要不断查询表中某个属性的应用程序。这是我现在正在做的事情。 我的服务类中的代码:

@Override
public int onStartCommand(Intent intent,int flags,int startId)
{
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
     ParseUser currentUser = ParseUser.getCurrentUser();
    String username = currentUser.getString("username");

    ParseQuery<ParseUser> query = ParseUser.getQuery();
     query.whereEqualTo("isAttacking", username);
    while(true)
    {
     query.findInBackground(new FindCallback<ParseUser>() {
          public void done(List<ParseUser> objects, ParseException e) {

              if ((e == null)&(objects.size() != 0))
            {
                // The query was successful.

                    ParseUser attacker = objects.get(0);
                    String attackerName = attacker.getUsername();
                    Log.i("ambustest",attackerName);
                    makeToast(attackerName);

            } else {
                Log.i("fd","Something went wrong.");
            }
          }

        });
     return START_STICKY;
    }

}

查询在无限循环中,但只执行一次。我最好的猜测是它在遇到 return 语句时会中断。有什么方法可以在不将 return 语句放入无法访问的代码的情况下保持循环运行?

4

2 回答 2

0

看起来你的线程混淆了。您的代码尝试启动此后台进程,然后START_STICKY一遍又一遍地返回。
即使您不必返回某些东西,您的进程也会尝试同时运行。

诀窍是从 的方法内部调用,query.findInBackground()也许在查询之间有一些合适的延迟项。这样你运行一个,然后当它完成时你开始下一个。这将消除整个 while 循环,从而使启动第一个后台查询然后返回变得简单done()FindCallBack

START_STICKY

于 2013-11-11T05:13:19.717 回答
0

尝试这个...

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    ParseUser currentUser = ParseUser.getCurrentUser();
    String username = currentUser.getString("username");

    ParseQuery<ParseUser> query = ParseUser.getQuery();
    query.whereEqualTo("isAttacking", username);
    findInBackground();
    return START_STICKY;
}

private void findInBackground() {
    while (true) {
        query.findInBackground(new FindCallback<ParseUser>() {
            public void done(List<ParseUser> objects, ParseException e) {

                if ((e == null) & (objects.size() != 0)) {
                    // The query was successful.

                    ParseUser attacker = objects.get(0);
                    String attackerName = attacker.getUsername();
                    Log.i("ambustest", attackerName);
                    makeToast(attackerName);

                } else {
                    Log.i("fd", "Something went wrong.");
                }
            }
        });
    }
}
于 2013-11-11T05:07:57.753 回答