not create new notification foreground android service - android

problem it once notification created but other notification not create and update last notification.
I want to get new notifications
call notification method :
private void NotificationLoop() {
// one notification
G.HANDLER.postDelayed(new Runnable() {
#Override
public void run() {
populateNotification(1, "task id : " + 1, 20);
}
}, 2000);
// two notification
G.HANDLER.postDelayed(new Runnable() {
#Override
public void run() {
populateNotification(2, "task id : " + 2, 40);
}
}, 2000);
// three notification
G.HANDLER.postDelayed(new Runnable() {
#Override
public void run() {
populateNotification(3, "task id : " + 3, 80);
}
}, 3000);
}
populateNotification my method from service :
private void populateNotification(int id, String title, int percent) {
Notification notification;
Intent CancelIntent = new Intent(this, ServiceDownload.class);
CancelIntent.setAction(Constant.ACTION.CANCEL_DOANLOAD_ACTION);
CancelIntent.putExtra("ID", id);
PendingIntent CCancelIntent = PendingIntent.getService(this, 0, CancelIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setTicker(title)
.setContentText(title)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setAutoCancel(false)
.setOngoing(false)
.addAction(android.R.drawable.ic_menu_close_clear_cancel, this.getResources().getString(R.string.Cancel), CCancelIntent)
.setProgress(100, percent, false)
.setStyle((new NotificationCompat.BigTextStyle().bigText(title)))
.build();
startForeground(id, notification);
}

Foreground Service has only one notification.
So when you call startForeground(id, notification); you just replace it.
You dont have much choice to solve your problem
Create new notification, not related to service
Stop foreground service and start it again, so notification will be
exactly new but there is possibility, that user will not notice
that it is new notification and not updated old notification .
Start new Foreground Service with new notification.

Related

Stopping Foreground service using NotificationCompat .addAction button

How would I stop the foreground service using the notification it creates in the class?
Intent stopnotificationIntent = new Intent(this, HelloIntentService.class);
//Not sure which is the current action to set
stopnotificationIntent.setAction("ACTION.STOPFOREGROUND_ACTION");
PendingIntent pIntent = PendingIntent.getService(this, 0, stopnotificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.addAction(0, "Cancel", pIntent);
startForeground(1111, notificationBuilder.build());
the button is created from .addAction and I want to stop that current foreground service
String ACTION_STOP_SERVICE= "STOP";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (ACTION_STOP_SERVICE.equals(intent.getAction())) {
Log.d(Statics.LOG_TAG,"called to cancel service");
stopSelf();
}
Intent stopSelf = new Intent(this, HelloIntentService.class);
stopSelf.setAction(ACTION_STOP_SERVICE);
PendingIntent pStopSelf = PendingIntent
.getService(this, 0, stopSelf
,PendingIntent.FLAG_CANCEL_CURRENT); // That you should change this part in your code
notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentText("Bla Bla Bla")
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pendingNotificationIntent)
.addAction(R.drawable.xxxx,"Close", pStopSelf)
.setSound(null)
.build();
startForeground(REQUEST_CODE, notification);
}

How do i give boolean status success or not to pendingIntent in broadcast Receiver

i'm developing addAction notification from iBeacon, how do i give boolean status success or not to this actionIntent from this pendingIntent notification which will received in onReceive method in ActionReceiver.class
this is the notification method from MainActivity.class
Intent broadcastIntent = new Intent(this, ActionReceiver.class);
broadcastIntent.putExtra("action", "notif1");
PendingIntent actionIntent = PendingIntent.getBroadcast(
this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.th_notif_logo)
.setTicker("Your Title")
.setWhen(System.currentTimeMillis())
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.addAction(R.drawable.ic_petunjuk_icon,"Clue", actionIntent)
.setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
.setStyle(new Notification.BigTextStyle().bigText(message))
.setContentIntent(pIntentAction)
.setPriority(Notification.PRIORITY_HIGH)
.build();
this is the onReceive method in ActionReceiver.class
#Override
public void onReceive(Context context, Intent intent) {
String action=intent.getStringExtra("action");
if(action.equals("notif1")){
SharedPreferences preferences = context.getSharedPreferences("MYPREFS", MODE_PRIVATE);
final String nama_tim = preferences.getString("username", "Key not correct");
InserData(nama_tim, "fsrd");
Toast.makeText(context.getApplicationContext(),"Action Receiver berhasil masuk",Toast.LENGTH_SHORT).show();
}
else if(action.equals("action2")){
}
//This is used to close the notification tray
Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(it);
}
so when i got boolean status success or not, i can do something in MainActivity.class
if (actionIntent == success){
//do something
}
really appreciate your help guys..
On your MainActivity.class
Intent broadcastIntent = new Intent("action-key"); // Specify the action to your intent.
broadcastIntent.setPackage(getPackageName());
// The values you want receive in the BroadcastReceiver.
broadcastIntent.putExtra("key-action", "notif1");
broadcastIntent.putExtra("key-boolean", true);
PendingIntent actionIntent = PendingIntent.getBroadcast(
this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT)
NotificationCompat.Action notificationAction = new NotificationCompat.Action(R.drawable.ic_action, "Action Name", actionIntent)
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = new NotificationCompat.Builder(this,"channelId")
.setSmallIcon(R.mipmap.ic_launcher)
.setTicker("Your Title")
.setWhen(System.currentTimeMillis())
.setContentTitle("test")
.setContentText("test")
.setAutoCancel(true)
.addAction(notificationAction) // Adds an action button to the notification
.setContentIntent(contentIntent) // Launches the intent when you click the notification.
.setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
.setPriority(Notification.PRIORITY_HIGH)
.build();
....
....
// Instead of using your own class receiver, you have to use the default default class receiver if you want your data to reach to your MainActivity.class easily.
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == "action") {
bool result = intent.getBooleanExtra("key-boolean", false); // Your value
}
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("action");
registerReceiver(broadcastReceiver, intentFilter);
Have you tried using public static boolean? Can you explain exactly when do you want your boolean to be true or false?

I want to show notification even if my Android app is running

I am using AWS SNS to send push notification to both SNS topics and Device Endpoints. It shows notification if the app is not running but does not show notification while the app is running.
I will like to show notification even if the app is running because the notification will inform the app user of changes happening in another section of the app so they can go check it out when they are ready. Something like getting notification of a new Whatsapp message from another group chat while you are typing message to another person.
Below is the notification builder code. Any hint will be really appreciated. Thanks.
private void displayNotification(final String message) {
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
int requestID = (int) System.currentTimeMillis();
PendingIntent contentIntent = PendingIntent.getActivity(this, requestID, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Bitmap large_icon = BitmapFactory.decodeResource(this.getResources(),
R.mipmap.myImage);
// Display a notification with an icon, message as content, and default sound. It also
// opens the app when the notification is clicked.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setLargeIcon(large_icon)
.setContentTitle("My Subject Title")
.setContentText(message)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setContentIntent(contentIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
}
I found the problem.
#Override
public void onMessageReceived(final String from, final Bundle data) {
String message = getMessage(data);
Log.d(LOG_TAG, "From: " + from);
Log.d(LOG_TAG, "Message: " + message);
// Display a notification in the notification center if the app is in the background.
// Otherwise, send a local broadcast to the app and let the app handle it.
displayNotification(message);
/* if (isForeground(this)) {
// broadcast notification
broadcast(from, data);
} else {
displayNotification(message);
} */
}
my displayNotification() function was not called because of the "if" conditional statement that will only display notification if the application is not in foreground. So now when onMessageReceived() gets the message it passes it directly to displayNotification() even if my application is currently running, which is what I want.
Use this below code to show notification message.
private static void generateNotification(Context context, final String message)
{
try {
NotificationManager mNotificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
//Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent notificationIntent = new Intent(context, DemoActivity.class);
notificationIntent.putExtra("message", message);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, RandomNumberGenerator.getRandom(),notificationIntent
/*new Intent(context, LuncherActivity.class)*/, 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context);
mBuilder.setSmallIcon(R.drawable.icon_small);
mBuilder.setContentTitle("YOUR-APP-NAME");
// mBuilder.setStyle(new NotificationCompat.BigTextStyle()
// mBuilder.bigText(msg);
mBuilder.setContentText(message);
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mBuilder.setSound(soundUri);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Create a random number genetor class like below
public class RandomNumberGenerator {
public static int getRandom()
{
int random_number=0;
Random random = new Random();
random_number= random.nextInt(9999 - 1000) + 1000;
return random_number;
}
}
Try it and let me know.its working in my case.

Android Notification Action not calling pending intent to service

I am trying to get my on going notification to have a button, when clicked it should call my service which is controlling audio playback.
Here is my notification with the intent
Intent intent = new Intent(context, AudioStreamService.class);
Random generator = new Random();
PendingIntent i = PendingIntent.getActivity(context, 579, intent,PendingIntent.FLAG_UPDATE_CURRENT);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(text)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setLargeIcon(picture)
.setTicker(ticker)
.setNumber(number)
.setOngoing(true)
.addAction(
R.drawable.ic_action_stat_reply,
res.getString(R.string.action_reply),
i);
notify(context, builder.build());
Here is the on start for my service
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("APP ID", "APP ID - service called ");
if(isPlaying){
stop();
}
else {
play();
}
return Service.START_STICKY;
}
The log is never triggered when called from the action in the notification. But the service is used by a button in the app and works fine. Log gets called as do commands below.
Use :
PendingIntent pendingIntent = PendingIntent.getService(context, 579, intent,PendingIntent.FLAG_UPDATE_CURRENT);
instead of :
PendingIntent pendingIntent = PendingIntent.getActivity(context, 579, intent,PendingIntent.FLAG_UPDATE_CURRENT);
^^ This is used to start an activity from the notification.

Make an intent kill a service

I'm trying to make a foreground notification for a service that has a button that when presses, will end the service. I have created the button but I have no idea what to make my intent to end the service.
public Notification getNotification(String message) {
Intent intent = new Intent(serviceContext, NotificationGenerator.class);
PendingIntent pi = PendingIntent.getActivity(serviceContext, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(serviceContext)
.setContentTitle(message)
.setContentText(message)
.setSmallIcon(R.drawable.icon)
.setContentIntent(pi)
.addAction(R.drawable.remove_button,"End Service", endService);
Notification n = builder.build();
n.defaults = Notification.DEFAULT_ALL;
return n;
}
Intent endService = new Intent();
What should I set endService to to do so?

Categories

Resources