1

I have working FCM notification in my android application. Everything is working.

My problem is, I dont want to show notification if the application is open.

here is my FirebaseMessagingService

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService{

    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        showNotification(remoteMessage.getData().get("title"),remoteMessage.getData().get("message"),remoteMessage.getData().get("type")
                ,remoteMessage.getData().get("src"),remoteMessage.getData().get("productid"),remoteMessage.getData().get("productname")
                ,remoteMessage.getData().get("categoryname"),remoteMessage.getData().get("categoryid"));
    }

    public Bitmap getBitmapFromURL(String strURL) {
        try {
            URL url = new URL(strURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void showNotification(String ttl,String msg, String type, String src, String pid, String pname, String cname, String cid) {

        mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notificationIntent = new Intent(this, MainActivity.class);
        Bundle extras = new Bundle();
        extras.putString("productFragment","productItem");
        extras.putString("productId",pid);
        extras.putString("productName",pname);
        extras.putString("categoryName",cname);
        extras.putString("categoryId", cid);
        notificationIntent.putExtras(extras);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        if (type.matches("text")) {
            Bitmap bitmap_logo = BitmapFactory.decodeResource(this.getResources(), R.drawable.mos);
            Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(this)
                            .setContentTitle(ttl)
                            .setContentText(msg)
                            .setLargeIcon(bitmap_logo)
                            .setSmallIcon(R.drawable.mos)
                            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                            .setAutoCancel(true)
                            .setSound(notificationSoundURI);
            mBuilder.setContentIntent(contentIntent);
            mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        }else if(type.matches("image")){
            Bitmap bitmap_logo = BitmapFactory.decodeResource(this.getResources(), R.drawable.mos);
            Bitmap bitmap_image=getBitmapFromURL(src);
            Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(this)
                            .setContentTitle(ttl)
                            .setContentText(msg)
                            .setLargeIcon(bitmap_logo)
                            .setSmallIcon(R.drawable.mos)
                            .setStyle(new NotificationCompat.BigPictureStyle()
                                    .bigPicture(bitmap_image)
                                    .setBigContentTitle(ttl)
                                    .setSummaryText(msg))
                            .setAutoCancel(true)
                            .setSound(notificationSoundURI);
            mBuilder.setContentIntent(contentIntent);
            mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        }
    }


}

I have no idea on how to do this. please help me.

thanks

Joe
  • 387
  • 1
  • 7
  • 22

1 Answers1

5

try this method,

public static boolean isAppInForeground(Context context) {
    List<ActivityManager.RunningTaskInfo> task =
            ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
                    .getRunningTasks(1);
    if (task.isEmpty()) {
        // app is in background
        return false;
    }
    return task
            .get(0)
            .topActivity
            .getPackageName()
            .equalsIgnoreCase(context.getPackageName());
}

which returns a boolean indicating app is in background or foreground

EDIT

Or you can do this way by providing package name

Use the below method with your package name. It will return true if any of your activities is in foreground.

public boolean isForeground(String myPackage) {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1); 
    ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
    return componentInfo.getPackageName().equals(myPackage);
}

Add Permission:

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

Hope this helps

Sanoop Surendran
  • 3,484
  • 4
  • 28
  • 49
  • sorry im new to android. in my case where to add this code? thanks. – Joe Jun 22 '17 at 05:07
  • add this code in any of the utlity class or application class (if you are using). then call by `className.isAppInForeground(anyActivityContextObject);` – Sanoop Surendran Jun 22 '17 at 05:08
  • thanks, i will try to implement this to my app so that the notification will not show when the app is open. im just trying to figure out where to put and when to call this. sorry for my english and for being noob. :D – Joe Jun 22 '17 at 05:24
  • 1
    and you need to call this before you actually call `showNotification` functionm like `if (!className.isAppInForeground(context) { showNotification... }` – Sanoop Surendran Jun 22 '17 at 05:26