BroadcastReceiver“action.USER_PRESENT”未被称为

时间:2017-03-30 14:38:03

标签: android broadcastreceiver screen android-broadcastreceiver

我正在尝试注册设备解锁事件。我使用带有action =“android.intent.action.USER_PRESENT”的接收器。

当应用程序处于活动状态时 - 一切正常。当我从最近推出的窗帘中删除一个应用程序 - 不起作用。这个问题在API21中很明显(4.4。 - 一切正常)。这是预料之中的,因为来自API21的谷歌认真致力于优化后台应用程序的工作,但这款接收器如何工作?清单代码:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.appdroid.develop.receiverscreenlock">
<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>
    <receiver android:name=".ScreenReceiver">
        <intent-filter android:priority="2147483647">
            <action android:name="android.intent.action.USER_PRESENT" />
        </intent-filter>
    </receiver>
</application>

班级代码:

public class ScreenReceiver extends BroadcastReceiver {

private static final String TAG = "myLog";

@Override
public void onReceive(Context context, Intent intent) {
    Log.d(TAG,"onReceive "+ intent.getAction());
    Toast.makeText(context,"screen unlock",Toast.LENGTH_SHORT).show();
}}

1 个答案:

答案 0 :(得分:0)

有人报告说清单中的设置没有帮助,所以请尝试在onCreate方法中进行此操作:

receiver = new ScreenReceiver()
IntentFilter i=new IntentFilter(Intent.ACTION_SCREEN_OFF);
        i.addAction(Intent.ACTION_SCREEN_ON);               
        registerReceiver(receiver ,i);

您无法通过清单中声明的​​组件接收此内容,只能通过使用Context.registerReceiver()source显式注册它,因此我认为如果您的应用程序被杀,您将无法收到。

但是你可以使用服务:

public static class UpdateService extends Service {

        @Override
        public void onCreate() {
            super.onCreate();
            // register receiver that handles screen on and screen off logic
            IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            BroadcastReceiver mReceiver = new ScreenReceiver();
            registerReceiver(mReceiver, filter);
        }

        @Override
        public void onStart(Intent intent, int startId) {
            boolean screenOn = intent.getBooleanExtra("screen_state", false);
            if (!screenOn) {
                // your code
            } else {
                // your code
            }
        }
}