android:用于屏幕和屏幕关闭的广播接收器

him*_*ura 58 android screen broadcastreceiver

我只是想知道是否可以在应用程序清单中注册检测屏幕ON/OFF的广播接收器.我不喜欢可编程方法的原因是它需要运行应用程序以便检测这样的事情,同时:"当Intent是Intent时,在清单中注册的广播接收器的应用程序不必运行广播接收器执行"(来源:专业Android 2应用程序开发书)

我的应用程序实际上是一个锁屏应用程序,通过使用可编程方式需要一直运行:S

有办法解决吗?

我在清单中尝试以下内容:

<receiver android:name=".MyBroadCastReciever">
    <intent-filter>
        <action android:name="android.intent.action.SCREEN_OFF"/>
        <action android:name="android.intent.action.SCREEN_ON"/>
    </intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)

和简单的MyBroadCastReciever类:

public class MyBroadCastReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            Log.i("Check","Screen went OFF");
            Toast.makeText(context, "screen OFF",Toast.LENGTH_LONG).show();
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            Log.i("Check","Screen went ON");
            Toast.makeText(context, "screen ON",Toast.LENGTH_LONG).show();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sad*_*amy 79

屏幕打开和关闭的两个操作是:

android.intent.action.SCREEN_OFF
android.intent.action.SCREEN_ON
Run Code Online (Sandbox Code Playgroud)

但是如果您在清单中为这些广播注册接收器,则接收器将不会接收这些广播.

对于此问题,您必须创建一个长时间运行的服务,该服务正在为这些意图注册本地广播接收器.如果你这样做,那么你的应用程序只会在你的服务运行时寻找屏幕,这不会刺激用户.

PS:在前台启动服务以使其运行更长时间.

一个简单的代码片段将是这样的:

IntentFilter screenStateFilter = new IntentFilter();
screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStateReceiver, screenStateFilter);
Run Code Online (Sandbox Code Playgroud)

不要忘记在服务onDestroy中取消注册接收器:

unregisterReceiver(mScreenStateReceiver);
Run Code Online (Sandbox Code Playgroud)

如果有人问为什么接收器不能使用ACTION_SCREEN_ON和ACTION_SCREEN_OFF的清单中的声明广播:

https://developer.android.com/reference/android/content/Intent.html#ACTION_SCREEN_ON https://developer.android.com/reference/android/content/Intent.html#ACTION_SCREEN_OFF

您不能通过在清单中声明的​​组件来接收它,只能通过使用Context.registerReceiver()显式注册它.

这是受保护的意图,只能由系统发送.

  • 好的,所以没有办法绕过它?这是锁屏应用程序的完成方式? (5认同)
  • 很好的答案,但为什么接收器不适用于清单中的这些广播? (4认同)
  • 如果您可以在清单中侦听ACTION_SCREEN_OFF,则操作系统必须为您的应用启动新流程(如果在触发广播时它未运行).Android设计人员希望防止这种情况,因为它通常意味着设备即将进入低功耗状态. (3认同)