4

I am using fcm to puch notification in my app but when the app is closed and cleared from recent apps then notification is not coming.I ma using FCM api to send notification to a particular topic. Note:- When the app is in background the notification is working fine

This is my FirebaseMessagingService Code

@RequiresApi(api = Build.VERSION_CODES.O)

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {


    String title = remoteMessage.getNotification().getTitle();
    String body = remoteMessage.getNotification().getBody();

    Map<String, String> extraData = remoteMessage.getData();

 Log.d("DATA",remoteMessage.getData().toString());

    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, "TAC")
                    .setContentTitle(title)
                    .setContentText(body)
                    .setSmallIcon(R.drawable.ic_launcher_background);





    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);


    int id =  (int) System.currentTimeMillis();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationChannel channel = new NotificationChannel("TAC","demo",NotificationManager.IMPORTANCE_HIGH);
        notificationManager.createNotificationChannel(channel);
    }
    notificationManager.notify(id,notificationBuilder.build());

}

}

this is Notification Sender class code

public class NotificationSender {

public  static RequestQueue mRequest;
public static String URL="https://fcm.googleapis.com/fcm/send";

public static void sendnotification(Context context,String sendto, String title, JSONObject extra){
    mRequest = Volley.newRequestQueue(context);
    JSONObject mainbody = new JSONObject();
    try {
        mainbody.put("to","/topics/"+sendto);
          mainbody.put("priority","high");
        JSONObject notification = new JSONObject();
        notification.put("title","New Notification");
        notification.put("body",title);
        mainbody.put("notification",notification);
          //  mainbody.put("data",extra);
            JSONObject data = new JSONObject();
            data.put("key",title);
            mainbody.put("data",data);


        JsonObjectRequest request=new JsonObjectRequest(Request.Method.POST, URL, mainbody, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> header = new HashMap<>();
                header.put("content-type","application/json");
                header.put("authorization","key=AIzaSyAfZqD0MW39WIGRBDFG0si3-HszFA");
               // AIzaSyAfZqD0MW39WIu9pWraYA0AG0si3-HszFA
                return header;
            }
        };
        mRequest.add(request);
    } catch (JSONException e) {
        e.printStackTrace();
    }






}

}

And This is my code to turn off battery optimization

 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        final Intent intent = new Intent();
        final String packageName = getPackageName();
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        if (!pm.isIgnoringBatteryOptimizations(packageName)) {
            AlertDialog ad= new AlertDialog.Builder(this).setTitle("IMPORTANT").setMessage("For The Proper Working Of The App,Please Disable Battery Optimization For This App").setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                    intent.setData(Uri.parse("package:" + packageName));
                    startActivity(intent);

                }
            }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finishAffinity();
                    System.exit(0);
                }
            }).create();
            ad.show();
        }
    }

2 Answers2

5

Many Chinese manufacturers kill the app's background services for saving battery. The running of your notification service is primary to receive push notifications. However, if you can remove your app from battery optimization in Settings, you'll receive push notifications when your app is in the background or you've killed the app. This might look like its silly, but when I had the same issue I removed my app from battery optimization and it worked!

mayur
  • 374
  • 1
  • 10
  • sir i have already turned off battery optimization.I have also posted the code for same – Abhishek Agarwal Apr 05 '20 at 19:04
  • Did you check in the Settings to see whether the code has removed your app from battery optimization? – mayur Apr 05 '20 at 19:11
  • There is a problem due to thecode the app ask to turn off battery optimization when I click turn off but then also it doesn't turn off my battery optimisation .But in some phone it's working after turning off it manually I am getting notifications Can you please share code to do it through program – Abhishek Agarwal Apr 06 '20 at 05:26
  • I don't think it is related. Even though I turn on the optimization, VOIP apps still work the same. – c-an Dec 27 '21 at 16:38
0

Like this:

mainbody.put("to","/topics/"+sendto);
mainbody.put("priority","high");
JSONObject data = new JSONObject();
data("title","New Notification");
data("body",title);
mainbody.put("data",data);

and

Map<String, String> extraData = remoteMessage.getData();

String title = extraData.get("title");
String body = extraData.get.get("body");
Kasım Özdemir
  • 5,414
  • 3
  • 18
  • 35