我正在使用 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.
如果我打开应用程序,我只想禁用警报,当应用程序关闭/暂停时,我想取消所有内容。
最佳答案
您需要创建一个具有全局状态的自定义应用程序
,并在应用程序级别实现您自己的onPause
和onResume
。
像这样创建您自己的应用程序子类:
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/