首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android -如何接收广播意图ACTION_SCREEN_ON/OFF?

Android -如何接收广播意图ACTION_SCREEN_ON/OFF?
EN

Stack Overflow用户
提问于 2009-10-19 11:01:12
回答 5查看 46.8K关注 0票数 67
    <application>
         <receiver android:name=".MyBroadcastReceiver" android:enabled="true">
                <intent-filter>
                      <action android:name="android.intent.action.ACTION_SCREEN_ON"></action>
                      <action android:name="android.intent.action.ACTION_SCREEN_OFF"></action>
                </intent-filter>
         </receiver>
...
    </application>

设置MyBroadcastReceiver只是为了将foo输出到日志。什么也不做。有什么建议吗?是否需要分配任何权限才能捕获意图?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2009-10-19 11:55:10

我认为,这些操作只能由在Java代码中注册的接收者(通过registerReceiver())接收,而不能通过清单中注册的接收者接收。

票数 70
EN

Stack Overflow用户

发布于 2011-09-07 17:55:23

或者,您可以使用电源管理器来检测屏幕锁定。

@Override
protected void onPause()
{
    super.onPause();

    // If the screen is off then the device has been locked
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    boolean isScreenOn;
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
        isScreenOn = powerManager.isInteractive();
    } else {
        isScreenOn = powerManager.isScreenOn();
    }

    if (!isScreenOn) {

        // The screen has been locked 
        // do stuff...
    }
}
票数 31
EN

Stack Overflow用户

发布于 2013-04-22 15:34:10

"android.intent.action.HEADSET_PLUG"
"android.intent.action.ACTION_SCREEN_ON"
"android.intent.action.ACTION_SCREEN_OFF"

上面的三个,他们不能使用Manifest注册。Android core向它们添加了"Intent.FLAG_RECEIVER_REGISTERED_ONLY“(也许..我只在"HEADSET_PLUG“的情况下检查了代码。

因此,我们应该使用“动态寄存器”。就像下面..。

private BroadcastReceiver mPowerKeyReceiver = null;

private void registBroadcastReceiver() {
    final IntentFilter theFilter = new IntentFilter();
    /** System Defined Broadcast */
    theFilter.addAction(Intent.ACTION_SCREEN_ON);
    theFilter.addAction(Intent.ACTION_SCREEN_OFF);

    mPowerKeyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String strAction = intent.getAction();

            if (strAction.equals(Intent.ACTION_SCREEN_OFF) || strAction.equals(Intent.ACTION_SCREEN_ON)) {
                // > Your playground~!
            }
        }
    };

    getApplicationContext().registerReceiver(mPowerKeyReceiver, theFilter);
}

private void unregisterReceiver() {
    int apiLevel = Build.VERSION.SDK_INT;

    if (apiLevel >= 7) {
        try {
            getApplicationContext().unregisterReceiver(mPowerKeyReceiver);
        }
        catch (IllegalArgumentException e) {
            mPowerKeyReceiver = null;
        }
    }
    else {
        getApplicationContext().unregisterReceiver(mPowerKeyReceiver);
        mPowerKeyReceiver = null;
    }
}
票数 28
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1588061

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档