【问题标题】:How to create notification when service is destroyed服务被销毁时如何创建通知
【发布时间】:2019-11-17 19:33:06
【问题描述】:

我正在尝试创建一个持续通知,该通知将在服务被销毁时出现。当用户点击通知时,服务应该重新启动,并且在服务被销毁时创建的通知应该消失。 下面是我正在使用的代码

   private boolean mRunning;

        @Override
 public void onDestroy(){
super.onDestroy();
destroyed();
Toast.makeText(getApplicationContext(),"you are offline",Toast.LENGTH_SHORT).show();
 }

 private void destroyed() {
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
    String Notichanid="com.g.kupa";
    String channelname="My Background";
    NotificationChannel chan=new NotificationChannel(Notichanid,channelname,NotificationManager.IMPORTANCE_HIGH);
    chan.setLightColor(Color.BLUE);
    chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    NotificationManager manager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    assert manager!=null;
    manager.createNotificationChannel(chan);
    Intent notificationintnet=new Intent(this,Profile.class);
    notificationintnet.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent contentIntent=PendingIntent.getActivity(this,0,notificationintnet,0);
    NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this,Notichanid);
    Notification notification=notificationBuilder.setOngoing(false)
            .setSmallIcon(R.drawable.menu_icon)
            .setContentTitle("You are offline")
            .setContentText("If you are awaiting one of your bookings to be accepted, tap this notification to get back online")
            .setPriority(NotificationManager.IMPORTANCE_HIGH)
            .setCategory(Notification.CATEGORY_SERVICE)
            .setContentIntent(contentIntent)
            .build();
    manager.notify(19,notification);

    if (!mRunning){
        mRunning=true;
        manager.cancel(19);
    }

以 if close 为特色的代码的最后一部分是新添加的。如果没有 if 通知,通知会出现,但当服务重新启动时,它仍然存在。 但是现在我已经添加了 if 语句来删除通知,当服务被销毁时,通知甚至没有出现,有人帮忙吗?

【问题讨论】:

    标签: java android service notifications


    【解决方案1】:

    好的。我发现stopForeground 函数有一个标志的可选参数而不是布尔值。可以给它一个标志STOP_FOREGROUND_DETACH,即使在调用stopForeground 之后,也有必要将通知从服务中分离出来,这样当服务被销毁时,通知不会被解除并且不必重新通知建成。这是我用于启动通知的更新代码:

    private fun updateNotification(preparing: Boolean = false) {
        if(getPlaying()) { 
            startService(Intent(applicationContext, this@MediaPlayerService.javaClass))
            startForeground(NOTIFICATION_ID, getNotification())
        }else {
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                stopForeground(Service.STOP_FOREGROUND_DETACH)
            else
                stopForeground(false)
            notificationManager.notify(NOTIFICATION_ID, getNotification())
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多