[![enter image description here][1]][1]
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.text.Html;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class FirebaseMessagingReceiveService extends FirebaseMessagingService {
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
private String the_message = "";
private String the_title = "ALERT_TITLE";
public static final String TAG = "FCM Demo";
private Context mContext;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage == null)
return;
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
try {
JSONObject json = new JSONObject(remoteMessage.getData().toString());
handleDataMessage(json);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
private void handleDataMessage(JSONObject json) {
Log.e(TAG, "push json: " + json.toString());
try {
the_title = json.getString("DgTitle");
the_message = json.getString("DgMessage");
sendNotification(the_message, the_title);
} catch (JSONException e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
private void sendNotification(String msg, String theTitle) {
mContext = getApplicationContext();
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> services = activityManager
.getRunningTasks(Integer.MAX_VALUE);
boolean isActivityFound = false;
if (services.get(0).topActivity.getPackageName().toString()
.equalsIgnoreCase(getPackageName().toString())) {
isActivityFound = true;
}
Intent openIntent = null;
if (isActivityFound) {
openIntent = new Intent();
} else {
openIntent = new Intent(this, MainActivity.class);
openIntent.putExtra("Title", the_title);
openIntent.putExtra("Message", the_message);
openIntent.setAction(Long.toString(System.currentTimeMillis()));
}
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
openIntent, PendingIntent.FLAG_ONE_SHOT);
if (msg != null && (!msg.isEmpty())) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setDefaults(Notification.DEFAULT_ALL)
.setVibrate(new long[]{100, 250, 100, 250, 100, 250})
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.activity_toolbar_color))
.setContentTitle(theTitle)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(Html.fromHtml(msg)))
.setPriority(Notification.PRIORITY_MAX)
.setContentText(Html.fromHtml(msg));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setSmallIcon(R.drawable.notification_icon1);
} else {
mBuilder.setSmallIcon(R.drawable.notification_icon);
}
mBuilder.setContentIntent(contentIntent);
SharedPreferences prefs = mContext.getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
int notificationNumber = prefs.getInt("notificationNumber", 0);
// create unique id for each notification
mNotificationManager.notify(notificationNumber, mBuilder.build());
SharedPreferences.Editor editor = prefs.edit();
if (notificationNumber < 5000)
notificationNumber++;
else
notificationNumber = 0;
editor.putInt("notificationNumber", notificationNumber);
editor.commit();
Log.d("notificationNumber", "" + notificationNumber);
}
}
}
this help to start FCM service in background when phone start.
>
> Add receiver in Manifest.xml
<uses-permission android:name="android.permission.WAKE_LOCK" />
<receiver android:name=".OnBootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
> OnBootBroadcastReceiver.class
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class OnBootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent("com.examle.FirebaseMessagingReceiveService");
i.setClass(context, FirebaseMessagingReceiveService.class);
context.startService(i);
}
}
> Add following dependency in app gradle.
//Used for firebase services
compile 'com.google.firebase:firebase-core:11.8.0'
compile 'com.google.firebase:firebase-messaging:11.8.0'
}
[1]: https://i.stack.imgur.com/lcCZK.png