2016-01-20 64 views
0

我與GCM聊天應用程序。當應用處於特定聊天活動的前臺時,我不想接收或顯示此通知。我該怎麼做?Android通知與GCM

這裏是我的通知:

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()); 
} 

回答

2

檢查ChatActivity是否在前臺或不保留一個變量。 boolean isActive;使這個變量false在和onDestroy中並使其在onResume中爲true。要訪問其他類中的此變量,請使用publicstatic以類名稱訪問它。

public static boolean isActive; 
 

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

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

現在在發送notificaton這個變量的校驗值。

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

0

您可以註銷GCM當你在前臺應用程序或節省SharedPreference應用狀態。

+0

我有很多聊天室,我不希望得到的只是從前臺聊天室推 – Drake

0

您可以檢查wheather是你的應用程序是forground或不受此

;

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"/> 
+0

權限被棄用 – Drake