I'm trying to send a notification from an IntentService.
I do get all the logs, but I don't get the notification (Using my galaxy s8 instead of an emulator).
I've tried to extend Service and I have tried to use a scheduler, but both did not work.
Service Code:
public class AppService extends IntentService {
private NotificationManager mNotificationManager;
public static final int NOTIFICATION_ID = 1;
public AppService() {
super("AppService");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
Log.d("AppService", "Started");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
Log.d("AppService", "Sending notification");
sendNotification("We might have some brand new movies to offer you!");
Log.d("AppService", "Notification sent");
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Log.d("AppService", "1");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Analyze.class), 0);
Log.d("AppService", "2");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentTitle("MyCienma")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setSmallIcon(R.drawable.icon_500x500_no_edge)
.setContentText(msg);
Log.d("AppService", "3");
mBuilder.setContentIntent(contentIntent);
Log.d("AppService", "4");
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d("AppService", "5");
}
}
I do get all the Logs, but I don't get any notification.
My project's min version is 21 and my phone is running 26. Is that a problem?
Yes, just because you have to set the notification channel id after android version 8.0(api 26).
Reference link:here
Hope! this will help you.
Happy coding...
After API v26 you have to define a NotificationChannel for every notification
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"YOUR_CHANNEL_NAME",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("YOUR_NOTIFICATION_CHANNEL_DISCRIPTION");
mNotificationManager.createNotificationChannel(channel);
}
Related
I'm developing a stopwatch that can show three notifications. When i update the notifications (every second), all of them are heading up in the notification bar, switching between them.
Is there any way to prevent them from moving to the top every time they are updated?
With the following code I create notifications from different services, each one with unique CHANNEL_ID and NOTIFY_ID.
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,getResources().getText(R.string.stopwatch_channel),
NotificationManager.IMPORTANCE_LOW
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
private Notification sendNotification(){
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(getResources().getText(R.string.stopwatch)+" ยท "+String.format("%02d:%02d:%02d",hour,min,secs))
.setSmallIcon(R.drawable.ic_stopwatch_24dp)
.setContentIntent(pendingIntent)
.setShowWhen(false)
.build();
return notification;
}
private void updateNotification() {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFY_ID, sendNotification());
}
I want to just Generate a notification after save Video.
for this i'll try below code :
public void stopRecordingVideo() {
ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
values.put(MediaStore.MediaColumns.DATA, file.toString());
activity.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
Toast.makeText(activity, "Video saved: " + file, Toast.LENGTH_SHORT).show();
//Log.v(TAG, "Video saved: " + getVideoFile(context));
Log.v(TAG, "Video saved: " + file);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(activity)
.setSmallIcon(R.drawable.ic_launcher_background) // notification icon
.setContentTitle("Notification!") // title for notification
.setContentText("Hello word") // message for notification
.setAutoCancel(true); // clear notification after click
Intent intent = new Intent(activity, RecorderActivity.class);
PendingIntent pi = PendingIntent.getActivity(activity,0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mBuilder.setContentIntent(pi);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
} else{
// do something for phones running an SDK before lollipop
}
try{
mMediaRecorder.stop();
mMediaRecorder.release();
}catch(RuntimeException stopException){
//handle cleanup here
}
try {
mSession.stopRepeating();
} catch (CameraAccessException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
setup2Record();
} else {
finish(); //just blows up anyway.
}
}
Video save perfectly in Storage and Toast msg also show. but only notification not generated please help for this solution.
Solution:
On Android 8.0 (Oreo) you must have something called as a NotificationChannel So try the below implementation:
Step1: Create Notification Channel
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
Finally: Then your Notification:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(activity)
.setSmallIcon(R.drawable.ic_launcher_background) // notification icon
.setContentTitle("Notification!") // title for notification
.setContentText("Hello word") // message for notification
.setAutoCancel(true); // clear notification after click
Intent intent = new Intent(activity, RecorderActivity.class);
PendingIntent pi = PendingIntent.getActivity(activity,0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mBuilder.setContentIntent(pi);
notificationManager.notify(1, mBuilder.build());
Try this, Hope it helps.
I have given my couple of days to solve this issue. My app is getting crash whose android version is 8.1. It is working perfectly fine in Android Version 8.0.
I followed the link mentioned below for the solution and tried many solutions given in this link but my application is not opening.
startForeground fail after upgrade to Android 8.1
I check the Android version in FirebaseMessageService class and create the channel for Oreo version but below given error is showing everytime
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:171)
at android.app.ActivityThread.main(ActivityThread.java:6649)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
Here below is my code. Please help me to rectify this problem
public class MyFirebaseMessagingService extends FirebaseMessagingService
{
private NotificationManager notifManager;
Context mContext;
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
#Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
sendNotification();
}
public void sendNotification()
{
Intent intent = new Intent(this, Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, m /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.app_icon)
.setContentTitle("Logipace")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND);
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, "LOGIPACE", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(m /* ID of notification */, notificationBuilder.build());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Below is the code which I used in the onCreate() method of my Activity class.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
// Create channel to show notifications.
String channelId = getString(R.string.default_notification_channel_id);
String channelName = getString(R.string.default_notification_channel_name);
NotificationManager notificationManager =
getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(new NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_LOW));
}
Help me to resolve this issue.
Put your logic inside onMessageReceived: Check Firebase quickstart sample.
public void onMessageReceived(RemoteMessage remoteMessage) {
// Handle data payload of FCM messages.
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Map<String, String> params = remoteMessage.getData();
JSONObject object = new JSONObject(params);
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
scheduleJob();
} else {
// Handle message within 10 seconds
final String msg = object.getString("msg");
sendNotification(msg);
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(getString(R.string.fcm_message))
.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());
}
I have found this Question : How to use startForeground? in Stackoverflow and as it says in the command from the top answer the notification constructor and setLastEventInfo is deprecated. I know that's a duplicated post but the other post is 4 years old and has no answer in the commends so I thought i try do ask it again maybe someone can help me with this.
Code:
Notification note = new Notification(R.drawable.ic_launcher,
"Foreground Service notification?", System.currentTimeMillis());
Intent i = new Intent(this, CurrentActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
Date dateService=new Date(System.currentTimeMillis());
String dateString=dateService.toString().split(" ")[1]+" "+dateService.toString().split(" ")[2]+" "+dateService.toString().split(" ")[3];
note.setLatestEventInfo(this, "Foreground service",
"Now foreground service running: "+dateString, pi);
note.flags |= Notification.FLAG_AUTO_CANCEL;
startForeground(2337, note);
You can use this method. Now with latest API versions you need to set channel for notifications.
private static final String NOTIFICATION_CHANNEL_ID ="notification_channel_id";
private static final String NOTIFICATION_Service_CHANNEL_ID = "service_channel";
.....
private void startInForeground() {
int icon = R.mipmap.icon;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
icon = R.mipmap.icon_transparent;
}
Intent notificationIntent = new Intent(this, CurrentActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notificationIntent,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(icon)
.setContentIntent(pendingIntent)
.setContentTitle("Service")
.setContentText("Running...");
Notification notification=builder.build();
if(Build.VERSION.SDK_INT>=26) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_Service_CHANNEL_ID, "Sync Service", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Service Name");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
notification = new Notification.Builder(this,NOTIFICATION_Service_CHANNEL_ID)
.setContentTitle("Service")
.setContentText("Running...")
.setSmallIcon(icon)
.setContentIntent(pendingIntent)
.build();
}
startForeground(121, notification);
}
When I click on the notification that pops up it doesn't open BaseApplication.class. What am I doing wrong here? I want the notification to open BaseApplication.class
public static void sendBasicNotification(int minor, int major, String task) {
Intent notifyIntent = new Intent(currentContext, BaseApplication.class);
notifyIntent.putExtra("t", task);
notifyIntent.putExtra("ma", major);
notifyIntent.putExtra("mi", minor);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(currentContext, 0, new Intent[] { notifyIntent },
PendingIntent.FLAG_UPDATE_CURRENT);
int notificationID = 21;
NotificationCompat.Builder builder = new NotificationCompat.Builder(currentContext)
.setContentText("You have started the task: " + task).setContentTitle("Task Alert")
.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true).setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis()).setDefaults(Notification.DEFAULT_ALL);
Notification notification = builder.getNotification();
NotificationManager notificationManager = getNotificationManager(currentContext);
notificationManager.notify(notificationID, notification);
}
static NotificationManager getNotificationManager(Context context) {
return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
Turns out I was sending the intent to the wrong class. Thanks all, fixed now. That code works just fine.
try adding this line
notifyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_SINGLE_TOP);
private void sendNotification(String msg) {
Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
// MainActivity is the Notification Intent that open by intent
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Application name")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d(TAG, "Notification sent successfully.");
}
hope it will work