Android Firebase push message in Android Studio - java

I have tried this code, but something happened unexpectedly. I can see a push message on my phone, but I can’t see the log in Android Studio. I think the method onMessageReceived isn’t working. Why did this happen?
My code follows.
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private boolean isVibrator = true;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
//vibrator();
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: "+remoteMessage.getNotification().getBody());
vibrator();
}
}
private void vibrator(){
if(isVibrator){
Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = {200,1000,150,1500,100,2000,50,3000};
vibe.vibrate(pattern, -1);
}
}
private void sendNotification(String messageBody) {
vibrator();
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)//.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
/* PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakelock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
wakelock.acquire(5000);*/
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
MyFirebaseInstanceIDService.java
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
Log.d(TAG, "send Server");
}
}

Related

Android - notification button from/to service

I created a running service that generates a notification with a button. I would like to create a listener in the service to do something when the button is pressed.
The notification is simple with an addaction statement.
I success on sending data to a external broadcaster receiver but no luck with a local one.
I'm just trying to change a boolean value of the service from the notification.
Thank you
public class TrackerService extends Service {
private static final int REQUEST_RESULT = 200;
final static String PANIC_ACTION = "PANIC";
private Point point = new Point();
private static final String TAG = "TrackerService";
private static final String NOTIFICATION_CHANNEL_ID = "tracker_service.channel";
private IntentFilter panicIntentFilter;
protected final IBinder binder = new TrackerServiceBinder();
public BroadcastReceiver trackerServiceBroadcastReceiver;
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
panicIntentFilter = new IntentFilter();
panicIntentFilter.addAction("PANIC");
this.registerReceiver(trackerServiceBroadcastReceiver, panicIntentFilter);
}
public class trackerServiceBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG + " TSRECEIVER","Complete intent: " + intent.toString() + " extras intent: " + intent.getExtras().toString());
if (intent.getAction().equals("PANIC") && intent.hasExtra("PANIC")){
if (intent.getExtras().getBoolean("PANIC")) {
//point.setPanicState(true);
Log.d(TAG + " TSRECEIVER", "panic pressed - point.getPanic(): " + "true");
} else {
//point.setPanicState(false);
Log.d(TAG + " TSRECEIVER", "panic pressed - point.getPanic(): " + "false");
}
}
}
}
public class TrackerServiceBinder extends Binder {
public TrackerService getServiceInstance() {
return TrackerService.this;
}
}
public Boolean TogglePanicState() {
point.setPanicState( !point.getPanicState() );
return point.getPanicState();
}
#RequiresApi(Build.VERSION_CODES.O)
private void startMyOwnForeground() {
Intent panicIntent = new Intent(this, trackerServiceBroadcastReceiver.class); // Prueba al broadcaster local
//Intent panicIntent = new Intent(this, TrackerService.class); // Prueba al servicio
//Intent panicIntent = new Intent(this, NotificationReceiver.class); // Prueba a un Broadcaster externo - Funciona
panicIntent.setAction("PANIC");
panicIntent.putExtra("PANIC", true);
PendingIntent panicPendingIntent = PendingIntent.getBroadcast(this, 123456, panicIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Log.d(TAG + " Notification","Complete intent: " + panicIntent.toString() + " extras intent: " + panicIntent.getExtras().toString() + " Complete PendingIntent: " + panicPendingIntent.toString());
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Tracker Service - Channel", NotificationManager.IMPORTANCE_NONE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.ou)
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.addAction(R.drawable.alarm, "PANIC", panicPendingIntent)
.build();
startForeground(1, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(trackerServiceBroadcastReceiver);
}
#Override
public IBinder onBind(Intent intent) {
return binder;
}
}

Specify time delay for sending Notification in Android Studio?

I have setup Notification Channels in Android Studio for sending my notifications.
So far, I can send a notification when I click a button.
However, I want to add a delay to when the notification is sent.. for example, send the notification after 20 seconds.
I know there is a function in the AlarmManager for System.getTimeInMillis, that would be related to this, but not sure where to go from here.
Here is my code:
public class MyNotificationPublisher extends Application {
public static final String CHANNEL_1_ID = "channel1";
public static final String CHANNEL_2_ID = "channel2";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannels();
}
private void createNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(
CHANNEL_1_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is Channel 1");
NotificationChannel channel2 = new NotificationChannel(
CHANNEL_2_ID,
"Channel 2",
NotificationManager.IMPORTANCE_LOW
);
channel2.setDescription("This is Channel 2");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
manager.createNotificationChannel(channel2);
}
}
}
public class EmailActivity extends AppCompatActivity {
private Button btnSend;
private NotificationManagerCompat notificationManager;
private long tenSeconds = 10000L;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email);
notificationManager = NotificationManagerCompat.from(this);
btnSend = findViewById(R.id.button_send);
}
public void sendOnChannel1(View v) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Hi")
.setContentText("Test")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
notificationManager.notify(1, notification);
}
}
You can just schedule the notifications to be sent :-
Use the following method :
public void scheduleNotification(Context context, long delay, int notificationId)
{
//delay is after how much time(in millis) from current time you want to schedule the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setContentTitle(context.getString(R.string.title)) .setContentText(context.getString(R.string.content)) .setAutoCancel(true) .setSmallIcon(R.drawable.app_icon) .setLargeIcon(((BitmapDrawable) context.getResources().getDrawable(R.drawable.app_icon)).getBitmap()) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Intent intent = new Intent(context, YourActivity.class);
PendingIntent activity = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(activity); Notification notification = builder.build();
Intent notificationIntent = new Intent(context, MyNotificationPublisher.class);
notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION_ID, notificationId);
notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notificationId, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
long futureInMillis = SystemClock.elapsedRealtime() + delay;
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
Then, the receiver class:
public class MyNotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification_id";
public static String NOTIFICATION = "notification";
#Override
public void onReceive(final Context context, Intent intent)
{
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int notificationId = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(notificationId, notification);
}
}
Then, call scheduleNotification with the appropriate arguments.
Use a handler to delay the execution of notification sending code
Update your code like that
public void sendOnChannel1(View v) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Hi")
.setContentText("Test")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
notificationManager.notify(1, notification);
}
}, 20000);
}

send notification when the user received a new message

I am trying to create a personal chat application for my college project. I have created the chat activity where the user can chat and receive the message, now I want to add the notification feature to it so that user can be notified at every message received by user, for this, I have searched all over the internet and found the FCM (firebase cloud messing) and tried to use it it didn't work.
below is the code that I have used to show a notification to the user.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
sendNotification(remoteMessage.getNotification().getBody());
Log.d(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
if (true) {
scheduleJob();
} else {
handleNow();
}
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
#Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);
sendRegistrationToServer(token);
}
private void scheduleJob() {
OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(MyWorker.class)
.build();
WorkManager.getInstance().beginWith(work).enqueue();
}
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, personalChat.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = "chat";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.logo)
.setContentTitle("Title")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
maybe I have used it in a wrong way ....help me so that I can complete my project

Notification is not displayed in notification drawer if app is in foreground

I am sending a notification into my app using Firebase cloud messaging and it's working fine. However, when I send a notification and if my app is in the foreground, the notification will not show in the notification tray. The notification only shows in the notification tray if my app is in the background.
Below is my code:
public class Notifications extends FirebaseMessagingService {
#ServerTimestamp
Date time;
private FirebaseFirestore mFirestore;
private boolean isNotificationMatching = false;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
mFirestore = FirebaseFirestore.getInstance();
if (remoteMessage.getData() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
sendNotificationAPI26(remoteMessage);
else
sendNotification(remoteMessage);
}
}
private void sendNotification(RemoteMessage remoteMessage) {
isNotificationMatching = false;
Intent intent = new Intent(this, Dashboard.class);
intent.putExtra("notificationFragment", "showNotifications");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
final Map<String, String> data = remoteMessage.getData();
String title = data.get("title");
mFirestore.collection("notifications").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
if (document.getData().get("id").equals(id)) {
isNotificationMatching = true;
break;
}
}
if (!isNotificationMatching) {
postDataToFirebaseServer(data);
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.app_logo)
.setContentText(description)
.setAutoCancel(true)
.setSound(defaultSoundUri);
builder.setContentIntent(pendingIntent);
NotificationManager noti = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
noti.notify(new Random().nextInt(), builder.build());
}
private void postDataToFirebaseServer(Map<String, String> data) {
Map<String, Object> postDataMap = new HashMap<>();
postDataMap.put("title", data.get("title"));
postDataMap.put("timestamp", FieldValue.serverTimestamp());
mFirestore.collection("notifications").add(postDataMap).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
// Toast.makeText(getA.this, "Success", Toast.LENGTH_SHORT);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
String error = e.getMessage();
// Toast.makeText(Testing.this, "Failed", Toast.LENGTH_SHORT);
}
});
}
private void sendNotificationAPI26(RemoteMessage remoteMessage) {
Intent intent = new Intent(this, Dashboard.class);
intent.putExtra("notificationFragment", "showNotifications");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
final Map<String, String> data = remoteMessage.getData();
String title = data.get("title");
mFirestore.collection("notifications").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
if (document.getData().get("id").equals(id)) {
isNotificationMatching = true;
break;
}
}
if (!isNotificationMatching) {
postDataToFirebaseServer(data);
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
NotificationHelper helper;
Notification.Builder builder;
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
helper = new NotificationHelper(this);
builder = helper.getLootBoxNotification(title, defaultSoundUri);
helper.getManager().notify(new Random().nextInt(), builder.build());
builder.setContentIntent(pendingIntent);
}
}
This is your code
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.app_logo)
.setContentText(description)
.setAutoCancel(true)
.setSound(defaultSoundUri);
builder.setContentIntent(pendingIntent);
Here you have set is as
setAutoCancel(true);
This method will cancel all the notification while your app is in foreground.
Set it to false.

How to show notification from broadcast receiver?

I am registering a broadcast receiver from a service. I need to show notification to user if location of device is off the code works fine but receiver does not create notification. I can see logcat messages on changing location status but notification is not created Please check the issue ! And is there any way to update the current notification of the service?
This is Service:
public class LockService extends Service {
BroadcastReceiver mReceiver;
Handler handler;
LocationManager locationManager;
#Override
public IBinder onBind(Intent intent) {
return null;
}
private static final int NOTIF_ID = 1;
#Override
public void onCreate() {
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
mReceiver = new com.example.fizatanveerkhan.citycops.ScreenReceiver();
registerReceiver(mReceiver, filter);
super.onCreate();
}
private void startForeground() {
startForeground(NOTIF_ID, getMyActivityNotification(""));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.startForeground();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
if (mReceiver != null) {
unregisterReceiver(mReceiver);
mReceiver = null;
Log.i("onDestroy Reciever", "Called");
}
super.onDestroy();
}
public class LocalBinder extends Binder {
LockService getService() {
return LockService.this;
}
}
private Notification getMyActivityNotification(String text) {
CharSequence title = "new";
Notification notification = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.abc)
.setContentTitle("Service running")
.setContentText("new")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
}
return notification;
}
/* public void updateNotification() {
String text = "Some text that will update the notification";
Notification notification = getMyActivityNotification(text);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIF_ID, notification);
}*/
}
And this is broadcast receiver:
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
private static final int POWER_OFF_TIMEOUT = 500;
private Handler handler = new Handler();
private Runnable powerOffCounterReset = new PowerOfTimeoutReset();
private int countPowerOff = 0;
private boolean screenOff;
//private LockService updateService = new LockService();
private final static String TAG = "LocationProviderChanged";
boolean isGpsEnabled;
boolean isNetworkEnabled;
#Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
Log.i(TAG, "Location Providers changed");
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
//Start your Activity if location was enabled:
if (isGpsEnabled || isNetworkEnabled) {
Log.i(TAG, "Location Providers on");
}
else {
Log.i(TAG, "Location Providers off");
Notification notification = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.abc)
.setContentTitle("Service running")
.setContentText("new")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, notification);
}
}
}
I can see logcat messages on changing location status but notification is not created
Changing notification code to this solved the problem
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String NOTIFICATION_CHANNEL_ID = "
com.example.fizatanveerkhan.citycops";
CharSequence name = "My Background Service";
String description = "My Background Service";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.abc)
.setContentTitle("Service running")
.setContentText("new")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
NotificationManagerCompat notificationManagerq =
NotificationManagerCompat.from(context);
// notificationId is a unique int for each notification that you must define
notificationManagerq.notify(1, notificationBuilder.build());
}
So basically you need to create a foreground notification and update its contents on location change.
You can use the code below to create a foreground notification:-
//for foreground service notification
public Notification showForegroundNotification(String notificationTitle, String notificationBody, Intent intent, ServiceName serviceName) {
String id = mContext.getString(R.string.upload_notification_channel_id);
PendingIntent lowIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext, id);
NotificationManager mNotifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = mContext.getString(R.string.upload_notification_channel_name);
String description = mContext.getString(R.string.upload_notification_channel_description); //user visible
int importance = NotificationManager.IMPORTANCE_LOW;
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(false);
mChannel.enableVibration(false);
mChannel.setVibrationPattern(new long[]{0L});
mChannel.setSound(null, att);
if (mNotifyManager != null) {
mNotifyManager.createNotificationChannel(mChannel);
}
notificationBuilder
.setSmallIcon(R.mipmap.ic_launcher)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setVibrate(new long[]{0L})
.setSound(null)
.setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
.setContentTitle(notificationTitle)
.setAutoCancel(true)
.setContentIntent(lowIntent);
} else {
notificationBuilder.setContentTitle(notificationTitle)
.setSmallIcon(R.mipmap.ic_launcher)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setVibrate(new long[]{0L})
.setSound(null)
.setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
.setAutoCancel(true)
.setContentIntent(lowIntent);
}
if (notificationBody != null) {
notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(notificationBody));
}
notificationBuilder.setContentText(notificationBody);
return notificationBuilder.build();
}
and you need to call startForegroundService();
private void startForegroundService(){
String dataTitle = SharedPrefer.getLastUpdatedLocationName();
String dataContent = SharedPrefer.getLastUpdatedLocation();
Intent intent = new Intent(WITHU.getAppContext(), MapLocateActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
startForeground(121, showNotification.showForegroundNotification(dataTitle, dataContent, intent, ServiceName.SMART_LOCATION, -1, false));
}
So it will pass the updated location name and location which you can collect from SharedPreference or also can be called directly onLocationChanged.

Categories