[英]Android Broadcast Receiver Not Working
I am trying to make my app print something to log when screen is turned on but it doesn't work as I expected.我试图让我的应用程序在屏幕打开时打印一些要记录的内容,但它没有按我的预期工作。
Here is what I have in my Manifest file这是我的清单文件中的内容
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity ...>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="PhoneBroadcastReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON"></action>
</intent-filter>
</receiver>
</application>
and my receiver looks like我的接收器看起来像
public class PhoneBroadcastReceiver extends BroadcastReceiver {
public PhoneBroadcastReceiver()
{
}
@Override
public void onReceive(Context _context, Intent _intent) {
// TODO Auto-generated method stub
String a = _intent.getAction();
MessageHandler.log("Received action: " + a); // just a wrapper for printing to a log
}
} }
but it prints nothing to the log.但它不会在日志中打印任何内容。 I keep pressing my Android power button and the screen turns on / turns off but my message doesn't appear in the log.
我一直按我的 Android 电源按钮,屏幕打开/关闭,但我的消息没有出现在日志中。 What am I missing?
我错过了什么? It looks the same as in examples I found on the web.
它看起来与我在 web 上找到的示例相同。
You cannot listen for ACTION_SCREEN_ON
broadcasts via a BroadcastReceiver
registered in the manifest.您无法通过清单中注册的
BroadcastReceiver
收听ACTION_SCREEN_ON
广播。 You have to register it via registerReceiver()
from a running component.您必须通过正在运行的组件中的
registerReceiver()
注册它。 There are fairly few broadcasts with this trait ( ACTION_SCREEN_OFF
, ACTION_BATTERY_CHANGED
, and perhaps ACTION_USER_PRESENT
).具有此特征的广播很少(
ACTION_SCREEN_OFF
, ACTION_BATTERY_CHANGED
,也许还有ACTION_USER_PRESENT
)。
ACTION_SCREEN_ON won't work if registered via manifest file.如果通过清单文件注册,ACTION_SCREEN_ON 将不起作用。 You need to register it dynamically.
您需要动态注册它。
maybe you forget to register the service on也许您忘记在
<application>
tag: <application>
标签:
<service android:name=".YourService" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.