kotlin 如何通过通知通道显示通知?

o8x7eapl  于 2023-03-03  发布在  Kotlin
关注(0)|答案(1)|浏览(152)

我正在创建一个应用程序,它使用前台服务和通知。服务工作正常,当我在设备上的开发者选项下检查运行服务时,它没有被系统杀死。但是,当我启动服务时,它没有在我的通知抽屉中显示通知。我是Kotlin的新手,我使用了一个旧的Java通知代码,我试着把代码转换成Kotlin,但是不起作用。根据我的研究,这应该起作用。我做错了什么?
这是我的项目代码
通知分类:

class NotificationService : Service() {

    private val CHANNEL_ID = "CHANNEL_ONE"

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

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
    }

    @SuppressLint("ObsoleteSdkInt")
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelName = "Photo Text Copier"
            val channelDescription = "Takes Snapshots and Copies the Text from Images!"
            val importance: Int = NotificationManager.IMPORTANCE_HIGH
            val channel = NotificationChannel(CHANNEL_ID, channelName, importance).apply {
                description = channelDescription
            }
            val notificationManager: NotificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
            sendNotification()
        }
    }

    private fun sendNotification(): Int {
        val builder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Photo Text Copier")
            .setContentText("Takes Snapshots and Copies the Text from Images!")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setWhen(System.currentTimeMillis())
            .build()

        startForeground(1, builder)
        return START_STICKY
    }

}

build.gradle项目:

plugins {
    id 'com.android.application' version '7.3.0' apply false
    id 'com.android.library' version '7.3.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.7.10' apply false
}

构建.gradle模块:

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    namespace 'com.mycompany.NotificationService'
    compileSdk 33

    defaultConfig {
        applicationId "com.mycompany.NotificationService"
        minSdk 26
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

    }

    buildFeatures {
        viewBinding true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }
    kotlinOptions {
        jvmTarget = '11'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.9.0'
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.8.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'com.getbase:floatingactionbutton:1.10.1'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.google.android.gms:play-services-vision:20.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}

settings.gradle

pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
        maven { url='https://jitpack.io'}
    }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        maven { url='https://jitpack.io'}
    }
}
rootProject.name = "NotificationService"
include ':app'

舱单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.NotificationService"
        tools:targetApi="33">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:screenOrientation="nosensor">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
        <service android:name=".NotificationService"/>
    </application>

</manifest>

从MainActivity类调用通知类:

serviceIntent = Intent(this, NotificationService::class.java)
                        startService(serviceIntent)

谢谢你的帮忙谢谢!

klsxnrf1

klsxnrf11#

我想出了我问题的答案。以下是对我有效的解决方案,以防将来有人遇到同样的问题。
在您的Manifest中添加以下内容:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
然后,您希望在MainActivity中向用户发出如下权限请求:

private lateinit var binding: ActivityMainBinding

    private val PERMISSION_NOTIFICATION: Int = 100

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.notificationServiceButton.setOnClickListener {
           notificationServicePermission()
        }
   }

  private fun notificationServicePermission() {
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        if (checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == 
             PackageManager.PERMISSION_DENIED) {
             val notificationPermission = (Manifest.permission.POST_NOTIFICATIONS)
             requestPermissions(arrayOf(notificationPermission), 
             PERMISSION_NOTIFICATION)
        }else{
             startNotificationService()
            }
     }else {
        startNotificationService()
      }
  }

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        when (requestCode) {
            PERMISSION_NOTIFICATION -> {
                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startNotificationService()
                }else{
                    Snackbar.make(binding.container, HtmlCompat.fromHtml("<b>Permission Denied!</b>",
                        HtmlCompat.FROM_HTML_MODE_LEGACY), Snackbar.LENGTH_SHORT).show()
                }
            }
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

private fun startNotificationService() {
        serviceIntent = Intent(this, NotificationService::class.java)
        startService(serviceIntent)
    }

相关问题