【问题标题】:Status bar notification click event Android for background foreground app state状态栏通知点击事件Android后台前台应用状态
【发布时间】:2014-06-27 05:21:13
【问题描述】:

点击状态栏通知。 我想检查如果我的应用程序处于前台状态,那么只有通知会取消,或者如果我的应用程序处于后台状态,它将打开我的应用程序。 我已在我的应用程序类中使用此代码管理我的应用程序状态

public static boolean isActivityVisible() {
    return activityVisible;
}

public static void activityResumed() {
    activityVisible = true;
}

public static void activityPaused() {
    activityVisible = false;
}

private static boolean activityVisible;

并将这些用于我的所有活动

@Override
protected void onResume() {
  super.onResume();
  MyApplication.activityResumed();
}

@Override
protected void onPause() {
  super.onPause();
  MyApplication.activityPaused();
}

通知我正在使用此代码

NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Notification notification = new Notification.Builder(context)
                .setContentTitle(title).setContentText(message)
                .setSmallIcon(R.drawable.ic_on).build();

        Intent notificationIntent = new Intent(context,
                AppStartActivty.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0,
                notificationIntent, 0);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        notification.defaults |= Notification.DEFAULT_SOUND;

        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0, notification);

我应该把这个条件放在哪里来检查应用程序状态和通知点击行为。 对不起我的英语不好

【问题讨论】:

  • 你想通过通知检查你的应用是在前台还是后台,对吧?
  • @MSS 是的,如果我的应用程序在后台,我想打开它,否则只通知取消
  • 是的,你可以通过实现服务来做到这一点。
  • @MSS 你能告诉我程序或任何演示链接。

标签: java android google-cloud-messaging android-pendingintent


【解决方案1】:

您可以使用以下代码检查您的应用是否处于后台/前台。

ActivityManager activityManager = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
            ArrayList<ActivityManager.RunningAppProcessInfo> appInfo = (ArrayList)activityManager.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo app : appInfo) {
                Log.d(TAG, "App: " + app.processName + "    State: " + (app.importance == 100 ? "Foreground" : "Background"));
                if (app.processName.equals(YourApp().getPackageName())) {
                    Log.d(TAG, app.processName);
                    if (app.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                       // Cancel notification
                    }
                    break;
                }
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2014-12-07
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多