gpt4 book ai didi

android - 为什么在Android中不调用onReceive扩展BroadcastReceiver

转载 作者:太空宇宙 更新时间:2023-11-03 12:21:05 34 4
gpt4 key购买 nike

由于某些原因没有调用 onReceive 方法
我没有应用任何过滤器或任何东西,

这是类:

import java.util.ArrayList;
import java.util.Calendar;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.Context;
import android.util.Log;

public class RegisterListener extends BroadcastReceiver {
private final int DELAY_TIME = 5;
private int m_seconds = 0;
private int m_minutes = 0;
private int m_hours = 0;
static ArrayList<BroadcastReceiverListener> listeners = new ArrayList<BroadcastReceiverListener>();

@Override
public void onReceive(Context context, Intent intent) {

Log.d("ScreenReceiver Action:",intent.getAction());

Calendar c = Calendar.getInstance();
m_seconds = c.get(Calendar.SECOND);
m_minutes = c.get(Calendar.MINUTE);
m_hours = c.get(Calendar.HOUR);

for (BroadcastReceiverListener listener:listeners){
listener.onReceive(m_hours, m_minutes, m_seconds);
}
}


public static void addBroadcastReceiveListener (BroadcastReceiverListener listener){
if(!listeners.contains(listener)){
listeners.add(listener);
}
}

public void removeBroadcastReceiveListener (BroadcastReceiverListener listener){
if(listeners.contains(listener)){
listeners.remove(listener);
}
}

这是 list 中的声明(应用程序的子级)

<receiver android:name=".RegisterListener"></receiver>

编辑:这是我尝试添加的过滤器(在 onReceive() 内)

    IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
BroadcastReceiver mReceiver = new RegisterListener();
registerReceiver(mReceiver, filter);

我收到一个错误:

The method registerReceiver(BroadcastReceiver, IntentFilter) is undefined for the type RegisterListener

最佳答案

如果您总是想监听 ACTION_USER_PRESENT,请尝试:

<receiver android:name=".RegisterListener">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>

解释

The method registerReceiver(BroadcastReceiver, IntentFilter) is undefined for the type RegisterListener

您必须将 registerReceiver() 与上下文一起使用,例如 context.registerReceiver(...)但是:

This is the filter i tried to add (inside the onReceive() )

onReceive() 中注册一个接收器是没有意义的,因为 onReceive() 在您注册一个接收器之前不会运行接收器...所以它永远不会发生。您可以将这段代码放在 Activity 的 onCreate() 中,如下所示:

IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
BroadcastReceiver mReceiver = new RegisterListener();
registerReceiver(mReceiver, filter);

这只会监听ACTION_USER_PRESENT您的应用已经在运行时。

关于android - 为什么在Android中不调用onReceive扩展BroadcastReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15706537/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com