我与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());
}
答案 0 :(得分:2)
要检查ChatActivity是否在前台,请保留一个变量。
boolean isActive;
在false
和onPause
中创建此变量onDestroy
,并在true
中将其设为onResume
。要在其他类中访问此变量,请使用public
和static
以类名访问它。
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();
}
答案 1 :(得分:0)
当您的应用处于前台或在SharedPreference上保存应用状态时,您可以取消注册GCM。
答案 2 :(得分:0)
您可以通过此
检查您的应用是否处于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"/>