
我有一个包含四个活动的应用程序,在应用程序中,用户会发现自己经常浏览4个活动.该应用程序还在后台提供持续服务,该服务显示状态栏通知,并侦听随后将显示在通知上的内容更改.
目前,只要用户启动需要显示通知的 *** 作,服务就会显示通知,因此,即使您仍在使用该应用程序,也会显示通知.所需方案是仅在用户导航出应用程序时显示通知.
我试图覆盖这样的生命周期方法:
@OverrIDeprotected voID onPause() { Intent intent = new Intent(); intent.setAction(MyService.ACTION_disPLAY_PENDING_NOTIFICATION); sendbroadcast(intent); super.onPause();}@OverrIDeprotected voID onResume() { super.onResume(); Intent intent = new Intent(); intent.setAction(MyService.ACTION_CANCEL_NOTIFICATION); sendbroadcast(intent); }服务是这样的:
@OverrIDe public voID onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ACTION_disPLAY_PENDING_NOTIFICATION)) { showNotification(); } else if (action.equals(ACTION_CANCEL_NOTIFICATION)) { mnotificationmanager.cancel(mNotID); } }这个,有效.但是,由于意图是在用户导航离开活动的任何时候发送的,因此当用户浏览4个活动时,我遇到了不良行为和轻微性能损失.即使从活动A到活动B,或者在4个活动中的任何组合,该服务也将尝试显示通知.
通知立即被取消,因为当新的活动B启动时,它将在onResume期间调用mnotificationmanager.cancel(mNotifID),但是通知已经构建并显示了几分之一秒,因为服务被告知在离开活动A时这样做这是我想解决的行为,而不是不必要地构建和显示这些通知,
有什么方法可以让我知道用户何时将活动转移到另一个应用程序,即主页等;但不在申请本身内?
编辑:
只是为了澄清,在onPause方法期间,活动必须检查两件事,
a)前景中是否有任何先前的活动?为什么?因为用户可以通过按回导航出活动,这意味着将显示堆栈上的最后一个活动.为了检查这一点,DennisDrew的答案可行,我们可以这样检查:
if(!ForegroundHelper.activityExistsInForeground()){//show your notification}但这不是用户可以导航出活动的唯一方式,用户也可以按HomeKey,在这种情况下,无论activityExistsInForeground()的计算结果为true还是false,都应显示通知.
b)用户是否要去应用程序中的其他活动?例如,用户在活动A上,A是前景中唯一的活动,用户点击启动活动B的UI元素.尽管activityExistsInForeground()评估为false,用户没有离开应用程序,他正在启动以前不在freground上的活动的新实例.
我试图在默认情况下添加私有布尔值launchNewActivity = false等标志,并在我知道我要进入另一个活动时将标志设置为true,例如在点击列表视图中的项目时:
litvIEw.setonItemClickListener(new OnItemClickListener() { @OverrIDe public voID onItemClick(AdapterVIEw<?> arg0, VIEw arg1, int arg2, long arg3) { launchingNewActivity = true startActivity2(arg2); } });然后在onPause期间检查:
@OverrIDeprotected voID onPause() { if(!ForegroundHelper.activityExistsInForeground() && launchingNewActivity){ //show your notification }但是这样做,它从不显示通知,不知怎的,双重检查总是默认为false.
解决方法:
如果使用单例引用怎么办?你可以创建一个类:
public static class ForegroundHelper { public static boolean[] activityStates = new boolean{false, false, false, false}; public static final int ACTIVITY_A = 0; public static final int ACTIVITY_B = 1; public static final int ACTIVITY_C = 2; public static final int ACTIVITY_D = 3; public static boolean activityExistsInForeground(){ for(boolean b : activityStates){ if(b) return true; } return false; }}然后,在每个活动的onResume()中执行:
//For your first activity (Activity A)ForegroundHelper.activityStates[ForegroundHelper.ACTIVITY_A] = true;并且在每个活动的onPause()中执行:
ForegroundHelper.activityStates[ForegroundHelper.ACTIVITY_A] = false;然后在每个活动的onStop()中执行:
if(!ForegroundHelper.activityExistsInForeground()){ //show your notification}顺便说一句,我从来没有做过这样的事情,所以我不知道它是否会像我编码那样完全正常工作……但是如果这有帮助,请告诉我.
总结以上是内存溢出为你收集整理的Android:仅在离开应用程序时显示Staus Bar Notificacion全部内容,希望文章能够帮你解决Android:仅在离开应用程序时显示Staus Bar Notificacion所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)