ama*_*sil 17 android android-service
只有当应用程序不在前台时,我才需要向用户显示通知.这是我的公共类MyFirebaseMessagingService扩展
FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if(applicationInForeground()) {
Map<String, String> data = remoteMessage.getData();
sendNotification(data.get("title"), data.get("detail"));
}
}
Run Code Online (Sandbox Code Playgroud)
需要实施applicationInForeground()方法
Bat*_*kun 21
您可以从android系统服务控制运行的应用程序进程.试试这个:
private boolean applicationInForeground() {
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> services = activityManager.getRunningAppProcesses();
boolean isActivityFound = false;
if (services.get(0).processName
.equalsIgnoreCase(getPackageName()) && services.get(0).importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
isActivityFound = true;
}
return isActivityFound;
}
Run Code Online (Sandbox Code Playgroud)
祝好运.
Dou*_*son 20
在Google I/O 2016上,我做了一个演讲,其中一个主题是Firebase如果您的应用程序位于前台后检测到的.您可以通过为应用中启动的每个活动递增一个计数器来使用ActivityLifecycleCallbacks,然后为每个停止的活动递减计数器.如果计数器> 1,那么您的应用程序就在前台.谈话的相关部分可以在YouTube上看到.
You could also try using Android Jetpack lifecycle components.
public class AppFirebaseMessagingService extends FirebaseMessagingService implements LifecycleObserver {
private boolean isAppInForeground;
@Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
@Override
public void onDestroy() {
super.onDestroy();
ProcessLifecycleOwner.get().getLifecycle().removeObserver(this);
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onForegroundStart() {
isAppInForeground = true;
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onForegroundStop() {
isAppInForeground = false;
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if(isAppInForeground) {
// do foreground stuff on your activities
} else {
// send a notification
}
}
}
Run Code Online (Sandbox Code Playgroud)
See here how to import the necessary dependencies, since lifecycle is not part of the standard Android SDK.
| 归档时间: |
|
| 查看次数: |
10808 次 |
| 最近记录: |