Android 与 GCM 的通知

Android notification with GCM

我有与 GCM 的聊天应用程序。当应用程序在特定聊天中处于前台时 activity 我不想接收或显示此通知。我该怎么做?

这是我的通知:

private void sendNotification(String message, String userId, String senderName) {
    Intent intent = new Intent(this, ChatActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("userId2", userId);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(senderName+" send message")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

    notificationManager.notify(0, notificationBuilder.build());
}

您可以在应用处于前台时注销 GCM 或将应用状态保存在 SharedPreference 上。

检查ChatActivity是否在前台保留一个变量。 boolean isActive;onPauseonDestroy 中将此变量设为 false,并在 onResume 中设为 true。要在其他 class 中访问此变量,请使用 publicstatic 以 class 名称访问它。

public static boolean isActive;

@Override
public void onResume() {
 super.onResume();
 isActive=true;
}
@Override
public void onPause() {
 super.onPause();
 isActive=false;
}

@Override
protected void onDestroy() {
 super.onDestroy();
 isActive=false;
}

现在发送通知时检查此变量的值。

if(!ChatActivity.isActive){
  sendNotification();
}

你可以通过这个检查你的应用是否在前台

;

import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.os.AsyncTask;

public class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

    @Override
    protected Boolean doInBackground(Context... params) {
        final Context context = params[0].getApplicationContext();
        return isAppOnForeground(context);
    }

    private boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null) {
            return false;
        }
        final String packageName = context.getPackageName();
        for (RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                    && appProcess.processName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }
}

并在您的清单中添加此权限

<uses-permission android:name="android.permission.GET_TASKS"/>