Display status bar notification from service in android

北城余情 提交于 2020-01-07 04:27:07

问题


Hi i've got a kind of a dumb problem. Im trying to display a notification from a service. When an activity starts i call the startService like so:

      Intent myIntent = new Intent(getApplicationContext(),notif_service.class);
      startService(myIntent); 

the service calculates something and should display the notification and then stop. the code is as follows:

    if (limit_time_value == 2 && start >= 6300000 && notif_past)
     {  

        notif_past=false;
        showNotification();
        stopSelf(); 

     }

There are two ways that this service can be stopped, ether from itself with stopSelf() or from a button in my activity with

           Intent myIntent = new Intent(getApplicationContext(),notif_service.class);
      stopService(myIntent);

the problem is that even when i stop the service the notification is shown after the specified time passes. I tried to stop the setvice with Binding it and than calling onDestroy() in which I cancel the notification and again call stopSelf(). Again the notification is shown.

What am I doing wrong? Do I misunderstand how notifications or services work?


回答1:


You do not indicate precisely where you are performing the work shown in your second code snippet above.

  • If that work is being done in onStart() or onStartCommand(), that work is being performed on the main application thread, and therefore once it starts it blocks all other main application thread work, such as stopService() and onDestroy().

  • If that work is being done on a background thread you create, unless you are terminating that background thread, that thread will continue to completion, regardless of whether the service is destroyed. You will need to arrange to terminate the thread yourself.




回答2:


Call the instance of the NotificationManager class which you have called inside the showNotification() function.

For example, I have used:

NotificationManager nm=(NotificationManager)this.getSystemService(this.NOTIFICATION_SERVICE);
nm.notify(1,builder.build());

If you have done something like this to create your notification, use the same instance to cancel it by calling cancel() function and passing the notificationId (in this case 1).

For example:

nm.cancel(1);

Here 1 denotes the notificationID which you have provided while creating it.



来源:https://stackoverflow.com/questions/4834620/display-status-bar-notification-from-service-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!