检查已过滤的 Intent 的操作

Checking an already filtered Intent for its action

我想每分钟运行一个任务,this问题已经和我的类似了。一位用户发布了以下内容:

BroadcastReceiver _broadcastReceiver;
private final SimpleDateFormat _sdfWatchTime = new SimpleDateFormat("HH:mm");
private TextView _tvTime;

@Override
public void onStart()
{
    super.onStart();
    _broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context ctx, Intent intent)
            {
                if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0)
                    _tvTime.setText(_sdfWatchTime.format(new Date()));
            }
        };

    registerReceiver(_broadcastReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}

@Override
public void onStop()
{
    super.onStop();
    if (_broadcastReceiver != null)
        unregisterReceiver(_broadcastReceiver);
}

我的问题是理解 onReceive 中的 if 语句。

  1. 为什么必须为 0?它说什么?
  2. 当我们已经为该操作设置了 IntentFilter 时,为什么首先要检查该操作 ACTION_TIME_TICK?

我会在原来的上下文中问这个问题,但我是 Whosebug 的新手。

Why does it have to be 0? What does it say?

好吧,让我们把它拆开。

intent.getAction()

如果您查看 right here,基本上它会告诉您意图在做什么。它 returns 一个字符串。 Intent.ACTION_TIME_TICK 实际上是一个字符串。

.compareTo() == 0

This 比较两个对象(在本例中为字符串)。当你检查它是否等于 0 时,你正在检查两个字符串是否相等,相同。

所以放在一起,

intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0

这会检查 Intent 的动作是否为广播动作 ACTION_TIME_TICK


Why is it necessary to check for the action ACTION_TIME_TICK in the first place, when we already set an IntentFilter with that action?

有时您会不小心(或故意)多次使用不同的 Intent 过滤器注册同一个 BroadcastReceiver。您的 BroadcastReceiver 将接收针对多个不同操作的广播。在 onReceive 方法中,您需要确保您正在响应适当的操作。