我想每分钟运行一个任务,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 语句。
- 为什么必须为 0?它说什么?
- 当我们已经为该操作设置了一个 IntentFilter 时,为什么有必要首先检查操作 ACTION_TIME_TICK?
我会在原始上下文中问这个问题,但我是 stackoverflow 的新手。
最佳答案
Why does it have to be 0? What does it say?
好吧,让我们把它分开。
intent.getAction()
如果你看right here ,基本上它会告诉您 Intent 在做什么。它返回一个字符串。 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
方法中,您需要确保您正在响应适当的操作。
关于android - 检查已过滤的 Intent 的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32551738/