首页 > 解决方案 > 应用程序关闭时意图过滤器不起作用

问题描述

我正在制作一个应用程序,每次屏幕解锁时都会显示通知。为此,我制作了一个启动服务的 BroadcastReceiver。这是我的清单:

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

    <application
        android:allowBackup="true"
        android:hardwareAccelerated="false"
        android:icon="@mipmap/ic_launcher"
        android:label="example"
        android:largeHeap="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".MainActivity"
            android:hardwareAccelerated="true"
            android:label="example" />

        <receiver android:name=".RestartNotifications"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT"/>
                <action android:name="android.intent.action.USER_PRESENT"/>
            </intent-filter>
        </receiver>

        <service
            android:name=".NotificationService"
            android:enabled="true"
            android:exported="true"/>
    </application>

</manifest>

广播接收器非常简单,如下所示:

public class RestartNotifications extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Hello World!", Toast.LENGTH_LONG).show();
        Intent i = new Intent(context, NotificationService.class);
        context.startService(i);
    }
}

我添加了一个 Toast 来检查错误是由于未接收到广播还是由于服务中的错误。当我安装该应用程序时,它运行良好,并且每次我解锁手机时都会出现通知,即使打开了另一个应用程序并且我的应用程序已停止。但是,如果我杀死我的应用程序,当我解锁手机时,通知将不再出现。

标签: androidservicenotificationsbroadcastreceiver

解决方案


您需要在服务上运行接收器。如果应用程序关闭,一个简单的接收器无法接收数据检查这个问题


推荐阅读