Android - 当应用程序处于后台时显示通知

标签 android notifications alarmmanager

我正在使用 AlarmManager 定期检查某个端点的新内容,验证来自端点的结果是否与我的应用程序中已有的结果相同,如果不相同则为每个项目创建一个通知.

我需要知道的是我应该如何让警报仅在应用程序暂停或停止时启动,并在应用程序启动或恢复时取消警报。

我应该在哪里启动警报以及我应该在哪里取消它们?

在 Android 通知指南中它说(在章节:何时不显示通知):

Don't create a notification if the relevant new information is currently on screen. Instead, use the UI of the application itself to notify the user of new information directly in context. For instance, a chat application should not create system notifications while the user is actively chatting with another user.

如果我打开应用程序,我只想禁用警报,当应用程序关闭/暂停时,我想取消所有内容。

最佳答案

您需要创建一个具有全局状态的自定义应用程序,并在应用程序级别实现您自己的onPauseonResume

像这样创建您自己的应用程序子类:

public class MyApplication extends Application {

    private static MyApplication sInstance;

    public MyApplication getInstance(){
        return sInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
    }

    public void onStart() {
        // TODO: Stop your notification.
    }

    public void onStop() {
        // TODO: Start your notification.
    }

}

在 AndroidManifest.xml 的标签中指定它的名字:

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:name="MyApplication">

创建一个类来保存 Activity 的计数:

public class ActiveActivitiesTracker {

    private static int sActiveActivities = 0;

    public static void activityStarted()
    {
        if (sActiveActivities == 0) {
            // TODO: Here is presumably "application level" resume
            MyApplication.getInstance().onStart();
        }
        sActiveActivities++;
    }

    public static void activityStopped()
    {
        sActiveActivities--;
        if (sActiveActivities == 0) {
            // TODO: Here is presumably "application level" pause
            MyApplication.getInstance().onStop();
        }
    }
}

然后创建一个基本 Activity (或在每个 Activity 中都这样做),只需调用 activityStarted()activityStopped() 方法:

@Override
public void onStart() {
    super.onStart();
    ActiveActivitiesTracker.activityStarted();
}

@Override
public void onStop() {
    super.onStop();
    ActiveActivitiesTracker.activityStopped();
}

有关自定义应用程序的更多详细信息,请参阅 this .

有关 Android 应用程序级暂停和恢复的更多详细信息,请参阅 this .

希望这对您有所帮助。

关于Android - 当应用程序处于后台时显示通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32076084/

相关文章:

java - Android 中广播接收器的 AlarmManager

android - 一个可以将项目 rebase 到 Google AOSP 的 Gerrit 实例?

android - Kotlin 数据类,将一个数据类的字段值复制到具有相同字段的另一个数据类

android - TextInputLayout 密码切换从中心移动文本

android - 当用户点击来自锁屏的通知时启动 Activity

android - Android API 15 及更高版本上的准确计时器

android - Google 拒绝了我的应用并声称存在广告欺诈

cocoa - 一定时间后隐藏 NSUserNotification

android - 从 Android 中的服务发送通知

android - 如何与 AlarmManager 一起启动通知?