Android - 应用程序在后台时显示通知

Android - Display notification when application is in background

我正在使用 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.

如果我打开了应用程序,我只想禁用警报,当应用程序处于 closed/paused 时,我想取消一切。

您可以尝试使用服务并在其中覆盖 onTrimMemory 方法,并在 "level" 等于 TRIM_MEMORY_UI_HIDDEN

时显示通知
@Override
public void onTrimMemory(int level) {
    super.onTrimMemory(level);
    switch (level) {
        case ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN:

            break;
    }

} 

查看文档以获取更多信息 http://developer.android.com/reference/android/content/ComponentCallbacks2.html#TRIM_MEMORY_UI_HIDDEN

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

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

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">

创建一个 class 来保存活动计数:

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

希望对您有所帮助。

我不确定这在您的项目中是否可行,或者它是否会实现您希望的结果,但是您可以从一个基础扩展所有活动 activity。在该基地 activity 的 onPause/onStop/onDestroy 方法中启动警报,在该基地活动 onCreate/onStart 方法中取消具有未决意图的警报。

这将为您提供一个设置位置,如果您有多个活动可能会关闭该应用程序,您可以从该位置处理警报。

您可以详细了解活动的生命周期here