检测到屏幕解锁

时间:2016-09-09 08:36:27

标签: java android screen android-broadcastreceiver unlock

我使用了那里的解决方案:Android - detect phone unlock event, not screen on

所以,我的活动onCreate:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    registerReceiver(
       new PhoneUnlockedReceiver(), new IntentFilter("android.intent.action.USER_PRESENT")
    );
}

我的接收器类:

public class PhoneUnlockedReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        KeyguardManager keyguardManager = 
            (KeyguardManager)context.getSystemService(Context.KEYGUARD_SERVICE);
        if (keyguardManager.isKeyguardSecure())
        {
            Toast.makeText(context, "Screen unlocked", Toast.LENGTH_LONG).show();
        }
    }
}

但是它不起作用,我的onReceive方法从未被调用过。任何想法有什么不对?

我的Android Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.example.michal.popupmenu"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

据我所知,如果我选择使用registerReceiver,则无需添加任何内容,对吗?

2 个答案:

答案 0 :(得分:1)

  

据我所知,如果我选择使用registerReceiver,则无需添加任何内容,对吗?

错误。清单中注册接收器的优点是,当Intent被触发时,它不需要您的应用程序运行。

因此,当用户解锁屏幕时,您的应用可能无法激活,因此没有调用registerReceiver(),因此您的接收器不会做出反应。

在清单中添加接收器,它将起作用。

答案 1 :(得分:0)

抱歉,但有人可以解释这个功能: 如果我没有设置PIN /模式/密码,addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.3") 总是返回false,设置PIN /模式/密码时返回true,尽管屏幕是锁定/解锁。 那么上面的代码如何运行:

sbt assembly

感谢。

相关问题