Android cancel ongoing notification not working - android

There seems to be other questions regarding cancelling ongoing notification.
However, i really look into quite a number of them and still have no solution.
SettingFragment
public class SettingFragment extends Fragment {
private Switch mSwitchNotific;
mSwitchNotific.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
Log.v(LOGTAG, "step notification on");
getContext().startService(new Intent(getContext(), UpdateStepNotificationService.class));
}else{
Log.v(LOGTAG, "step notification off");
NotificationManager notificationManager = (NotificationManager)
getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(StickyUpdateStepNotification.NOTIFICATION_ID);
}
}
}
}
UpdateStepNotificationService
public class UpdateStepNotificationService extends Service {
static NotificationManager notificationManger;
StepsDBHandler stepsDBHandler;
public UpdateStepNotificationService() {}
#Override
public void onCreate() {
super.onCreate();
stepsDBHandler = new StepsDBHandler(getApplicationContext(), null, null, 0);
notificationManger = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
StickyUpdateStepNotification.NOTIFICATION_ID,
new Intent(getApplicationContext(), MainActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
final Notification notification = new Notification.Builder(
getApplicationContext())
.setSmallIcon(R.drawable.ic_notice)
.setContentTitle("Walksapp")
.setContentText("Now: " +Integer.toString(stepsDBHandler.getCurrentStepToday()) + " steps")
.setContentIntent(pendingIntent)
.build();
notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
new Timer().schedule(new TimerTask() {
#Override
public void run() {
notificationManger.notify(StickyUpdateStepNotification.NOTIFICATION_ID, notification);
}
}, 0, 1000);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onDestroy() {
notificationManger.cancel(StickyUpdateStepNotification.NOTIFICATION_ID);
super.onDestroy();
}
}
UpdateStepNotificationService for repeating issue new notification with latest step count.
The notification is with FLAG_NO_CLEAR and FLAG_ONGOING_EVENT.
The only way turn on and off the notification is by switch button in SettingFragment.
Attempt:
notificationManger.cancel(StickyUpdateStepNotification.NOTIFICATION_ID);
Not working
Hope to see any input
Thanks

You will need to kill the timer otherwise it will continue updating the notification.

Related

Service stopForeground(false) remove notification when should not

Instead of
stopForeground(true)
calling,
stopForeground(false)
should retain the notification as it is (without ongoing state) unless it is dismissed by user/removed programmatically.
This also should prevents notification flashing since I am not recreating the notification.
But it does not work. stopForeground(false) has the same behavior of stopForeground(true).
This is a sample project:
public class AudioTestService extends Service {
private static final String CHANNEL_ID = "TestChannel";
private static final int NOTIFICATION_ID = 14;
Notification mBuilder;
public AudioTestService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
return null;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
stopForeground(true);
super.onTaskRemoved(rootIntent);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent intentA = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intentA, 0);
Notification mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Titolo")
.setContentText("Descrizione")
.setContentIntent(pendingIntent)
.setOngoing(false)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build();
this.mBuilder = mBuilder;
createNotificationChannel();
startForeground(NOTIFICATION_ID, mBuilder);
return START_STICKY;
}
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = CHANNEL_ID;
String description = CHANNEL_ID + "Description ";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(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 = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
#Override
public void onDestroy() {
stopForeground(false);
//NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, mBuilder);
super.onDestroy();
} }
The activity, easily handle the button click event:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startService = findViewById(R.id.startService);
Button stopService = findViewById(R.id.stopService);
Button stopNotification = findViewById(R.id.stopWithNotification);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
stopNotification.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.startService:
ContextCompat.startForegroundService(this, new Intent(this, AudioTestService.class));
break;
case R.id.stopService:
finish();
break;
case R.id.stopWithNotification:
stopService(new Intent(this, AudioTestService.class));
break;
}
}}
If you look at the Service's onDestroy() method I set
stopForeground(false);
instead of the method onTaskRemoved() that should remove the notification when the app is cleaned from the task list.
What am I doing wrong?
Please do not mark this as duplicated, I am looking for a solution for days...
Instead of calling stopForeground(false); from onDestroy(), send a broadcast from activity (with action) for stop service. Change your onStartCommand code to check action in intent and do startForeground or stopForeground(false);

Why in IntentService super.OnCreate delete a notification startForeground()

I'm continuing in the Android studies and i've a questions.
I'have this intentService:
public class SystemService extends IntentService{
public SystemService() {
super("SystemService");
}
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, startId, startId);
return(START_NOT_STICKY);
}
#Override
public void onCreate(){
super.onCreate();
startForeground();
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void startForeground(){
Intent notificationIntent = new Intent(this, DashboardActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification noti = new Notification.Builder(getApplicationContext())
.setContentTitle("Foregroundservice")
.setContentText("foreground is active")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent).build();
startForeground(1337, noti);
}
}
Why, in onCreate() function, if I put the function startForeground() so, ne initializing foregroundservice before the super.onCreate(), the foreground notify disappear But if a put after seem work?

The same push notification keeps appearing whenever i open my apps

The same push notification keeps appearing whenever I reopen my apps although i have already cleared the notification in the notification bar. Secondly how do I implement a service so that my apps can receive notification although the apps is closed.
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARED_PREF, MODE_PRIVATE);
String id = sharedPreferences.getString(Constants.UNIQUE_ID, null);
Firebase firebase = new Firebase(Constants.FIREBASE_APP + id);
firebase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
String msg = snapshot.child("msg").getValue().toString();
if (msg.equals("none"))
return;
showNotification(msg);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("The read failed: ", firebaseError.getMessage());
}
});
return START_STICKY;
}
private void showNotification(String msg){
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher);
Intent intent = new Intent(NotificationListener.this,ViewRecord.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentIntent(pendingIntent);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("Notifier");
builder.setContentText(msg);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
builder.setAutoCancel(true);
notificationManager.notify(1, builder.build());
}
my service code as below. and i call the service at onCreate function in the 1st activity..
public class MyService extends Service {
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// For time consuming an long tasks you can launch a new thread here...
Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();
}
}
Posting this as answer since code in comment wud make it look unstructured
isServiceStarted
public class MainActivity extends AppCompatActivity {
private SharedPreferences servicePref;
private boolean isServiceStarted;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
servicePref = getSharedPreferences("servicePref", MODE_PRIVATE);
isServiceStarted = servicePref.getBoolean("isServiceStarted", false);
if (!isServiceStarted) {
startService(new Intent(this, MyService.class));
servicePref.edit().putBoolean("isServiceStarted",true).apply();
}
}
and in ur MyService.class inside onStop method do this without fail.
public class MyService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
// save value as false when service gets destroyed so as to start again when u open the app
getSharedPreferences("servicePref", MODE_PRIVATE).edit().putBoolean("isServiceStarted",false).apply();
}
}
override the onStartCommand() method and then return START_STICKY.

Service never gets garbage collected

My application has a button : "Foreground". By clicking on the foreground button, a notification appears attached to a foreground service (started at the time of click). Clicking on my notification is supposed to stop my service (with a PendingIntent) to be able to be garbage collected, however, this is not the case. Android Studio tells me, that there is a reference to my Service held by a NotificationManager. The weird thing is that it only happens if I click on my notification after I closed the main activity.
My service code:
public class TestService extends IntentService {
public static final String ACTION_GO_FOREGROUND = "GO_FOREGROUND";
public static final String ACTION_DESTROY = "DESTROY";
private NotificationManagerCompat notificationManager;
public TestService() {
super("Name");
}
#Override
public void onCreate() {
super.onCreate();
notificationManager = NotificationManagerCompat.from(this);
}
#Override
public void onDestroy() {
super.onDestroy();
notificationManager.cancelAll();
notificationManager = null;
}
#Override
protected void onHandleIntent(Intent intent) {
}
#Override
public int onStartCommand(Intent intent, int flags, final int startId) {
switch (intent.getAction()) {
case ACTION_GO_FOREGROUND:
fg();
break;
case ACTION_DESTROY:
destruct();
break;
}
return START_STICKY;
}
private void destruct() {
stopForeground(true);
stopSelf();
}
private void fg() {
Intent intent = new Intent(this, TestService.class);
intent.setAction(ACTION_DESTROY);
// Create the notification.
android.support.v7.app.NotificationCompat.Builder notificationBuilder = new android.support.v7.app.NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setTicker("Ticker");
notificationBuilder.setContentTitle("Title");
notificationBuilder.setContentText("Content text");
notificationBuilder.setContentIntent(PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
startForeground(1, notificationBuilder.build());
}
I know the code is messy, but it's just a sample. So why is there a reference to my service, but only if you close the activity and try to destroy the service?
Try removing the code from OnDestroy -
notificationManager.cancelAll();
notificationManager = null;
and place it in destruct() before calling stopSelf()

Continue service when app is killed

I have an activity with two buttons (ON and OFF): when I click the ON button a service starts. When I click the OFF botton the service stops. Now, my service does not have problems apart from when I kill the app from "Recent Apps" because in this circumstance the service restarts. I don't want that it restarts but I want that it continues working. The service is a START_STICKY.
This is my "service" code:
#Override
public void onCreate() {
// TODO Auto-generated method stub
myServiceReceiver = new MyServiceReceiver();
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar.
showNotification();
}
public class LocalBinder extends Binder {
SensorService getService() {
return SensorService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if (!running){
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MY_ACTION_FROMACTIVITY);
registerReceiver(myServiceReceiver, intentFilter);
running = true;
sensorManager=(SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), SensorManager.SENSOR_DELAY_NORMAL);
}
//return super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onDestroy() {
Log.v(TAG,"destroy");
// TODO Auto-generated method stub
sensorManager.unregisterListener(this);
mNM.cancel(NOTIFICATION);
this.unregisterReceiver(myServiceReceiver);
super.onDestroy();
}
private void showNotification() {
CharSequence text = getText(R.string.activity);
Notification notification = new Notification(R.drawable.lifestyle, text, System.currentTimeMillis());
SharedPreferences flagNot = getSharedPreferences("flagNotification", 0);
final SharedPreferences.Editor editor = flagNot.edit();
editor.putBoolean("flagNotification",true);
editor.commit();
Intent notificationIntent = new Intent(this, ActivityTab.class);
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.app_name),text, contentIntent);
notification.flags |= Notification.FLAG_NO_CLEAR;
// Send the notification.
mNM.notify(NOTIFICATION, notification);
}
public void onAccuracyChanged(Sensor sensor,int accuracy){
}
public void onSensorChanged(SensorEvent event){
......
}
public class MyServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
int hostCmd = arg1.getIntExtra(CMD, 0);
if(hostCmd == CMD_STOP){
running = false;
stopSelf();
}
}
}
}
Can you help me,please?
Many thanks.
Implement startForeground in your service and send it a persistent notification.
private void startForeground() {
int ID = 1234;
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification.Builder builder = new Notification.Builder(getBaseContext());
builder.setContentIntent(pendIntent);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setTicker("CUSTOM MESSAGE");
builder.setWhen(System.currentTimeMillis());
builder.setAutoCancel(false);
builder.setContentTitle("Test Service");
builder.setContentText("CUSTOM MESSAGE");
Notification notification = builder.build();
startForeground(ID, notification);
}

Categories

Resources