android - 应用程序关闭时意图过滤器不起作用
问题描述
我正在制作一个应用程序,每次屏幕解锁时都会显示通知。为此,我制作了一个启动服务的 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 来检查错误是由于未接收到广播还是由于服务中的错误。当我安装该应用程序时,它运行良好,并且每次我解锁手机时都会出现通知,即使打开了另一个应用程序并且我的应用程序已停止。但是,如果我杀死我的应用程序,当我解锁手机时,通知将不再出现。
解决方案
您需要在服务上运行接收器。如果应用程序关闭,一个简单的接收器无法接收数据检查这个问题
推荐阅读
- sql - 错误:列中的空值违反非空约束
- json - phpunit 断言 json_encode 数组
- javascript - Lodash:带有无关紧要的真值表
- spring - 是否可以更改弹簧启动执行器中的端点名称
- python - pandas html 函数转换为浮点数
- android-recyclerview - 在recyclerview上方滚动viewpager标题不起作用
- python - Googletrans API 属性错误
- pandas - 删除第一个或最后一个字符,以便列中的值应以数字开头
- lua - 使用旋转块脚本时,Roblox 部件未正确碰撞
- c# - Crystal Reports 在不同环境下登录失败