android - Android Studio 中 unbindService 会自动清理通知图标吗?

标签 android android-service

以下代码来自project .

启动bindService()时会显示通知图标,没问题。

但是当我启动unbindService()时,通知图标不会被清除,为什么?我在以下代码中找不到任何代码来清理通知图标。

MainActivity.kt

class MainActivity : AppCompatActivity(), View.OnClickListener {
    val mTAG = MainActivity::class.java.simpleName
    // Variable for storing instance of our service class
    var mService: MyBoundService? = null

    // Boolean to check if our activity is bound to service or not
    var mIsBound: Boolean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        startServiceButton?.setOnClickListener(this)
        stopServiceButton?.setOnClickListener(this)
        startActivityButton?.setOnClickListener(this)
    }


    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(className: ComponentName, iBinder: IBinder) {
            Log.d(mTAG, "ServiceConnection: connected to service.")
            // We've bound to MyService, cast the IBinder and get MyBinder instance
            val binder = iBinder as MyBinder
            mService = binder.service
            mIsBound = true
            getRandomNumberFromService() // return a random number from the service
        }

        override fun onServiceDisconnected(arg0: ComponentName) {
            Log.d(mTAG, "ServiceConnection: disconnected from service.")
            mIsBound = false
        }
    }

    /**
     * Method for listening to random numbers generated by our service class
     */
    private fun getRandomNumberFromService() {
        mService?.randomNumberLiveData?.observe(this
                , Observer {
            resultTextView?.text = "Random number from service: $it"
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        // Unbinding to the service class
        unbindService()
    }


    private fun bindService() {
        Intent(this, MyBoundService::class.java).also { intent ->
            bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
        }
    }


    private fun unbindService() {
        Intent(this, MyBoundService::class.java).also { intent ->
            unbindService(serviceConnection)
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.startServiceButton -> {
                bindService()
            }
            R.id.stopServiceButton -> {
                if (mIsBound == true) {
                    unbindService()
                    mIsBound = false
                }
            }
            R.id.startActivityButton -> {
                val intent = Intent(this, ResultActivity::class.java)
                startActivity(intent)
            }
        }
    }
}

MyBoundService.kt

class MyBoundService : Service() {
    ...

    override fun onBind(intent: Intent): IBinder? {
        return mBinder
    }

    override fun onCreate() {
        super.onCreate()
        Log.d("MyBoundService", "onCreate called")
        startNotification()

        Handler().postDelayed({
            val randomNumber = mGenerator.nextInt(100)
            randomNumberLiveData.postValue(randomNumber)
        }, 1000)
    }

  
    private fun startNotification() {
        val channel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel(
                    CHANNEL_ID,
                    "My Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            )
        } else {
            TODO("VERSION.SDK_INT < O")
        }
        (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel)
        val notification: Notification = NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("A service is running in the background")
                .setContentText("Generating random number").build()
        startForeground(1, notification)
    }
}

最佳答案

确实如此,MyBoundService 的代码调用 startForeground(),这允许 MyBoundService 即使在 MainActivity 时也能继续运行code> 会被销毁或不在前台运行,直到 Android 操作系统出于释放内存等原因决定停止 MyBoundService

要停止MyBoundService并删除通知,需要调用stopForeground(true),然后调用stopSelf()。您可以使用您拥有的示例代码添加以下内容来实现此目的:

MainActivity.kt

    private fun unbindService() {
        Intent(this, MyBoundService::class.java).also { intent ->
            unbindService(serviceConnection)
            mService.stopForeground(true)
            mService.stopSelf()
        }
    }

关于android - Android Studio 中 unbindService 会自动清理通知图标吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64086425/

相关文章:

android - 如何在 Android 项目中使用 Ant build.xml 包含 .jar 文件

android - 检测 DialogFragment 中的用户不活动并在一段时间后注销

java - Android开机启动服务,无法接收广播

java - 使用 ShareActionProvider 共享内容时检测成功/失败

android - 了解前台服务生命周期

android - 组织包含 XML 布局文件

android - 使用 ParcelFileDescriptor.createPipe() 将 InputStream 传输到另一个服务(跨进程边界)失败,返回 "EBADF (Bad file number)"

java - 可以在应用程序而不是 Activity 上调用 startService 吗?

android - 始终在后台以 root 身份在 android 上运行服务

android - 如何在 Android 中使用警报管理器启动服务?