服务被破坏时如何创建通知

问题描述 投票:0回答:1

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

   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结束符是新增的。如果没有if通知,则显示该通知,但是当服务重新启动时,它将保留。但是,现在我已经添加了if语句来删除通知,该通知甚至在服务被销毁时甚至都没有出现,有人可以提供帮助吗?

java android service notifications
1个回答
0
投票

好。我发现stopForeground函数具有标志的可选参数,而不是布尔值。可以给它提供一个标志STOP_FOREGROUND_DETACH,即使在调用stopForeground之后也需要将该标志从服务中分离出来,这样,当服务被破坏时,该通知将不会被取消,并且不必重新创建通知内置的。这是我用于启动通知的更新代码:

private fun updateNotification(preparing: Boolean = false) {
    if(getPlaying()) { 
        startService(Intent(applicationContext, [email protected]))
        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())
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.