我正在尝试用Kotlin做一个Android应用,每当日期改变、屏幕打开或手机启动时,它都会给我发送一个通知
我尝试使用BroadcastReceiver发送通知,但不起作用。这里是BroadcastReceiver
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
class SendNotification: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == Intent.ACTION_DATE_CHANGED || intent?.action == Intent.ACTION_SCREEN_ON || intent?.action == Intent.ACTION_BOOT_COMPLETED){
println(intent)
println(context)
val hours = TOTKTime.getHours()
val days = TOTKTime.getDays()
val notificationManager = context?.getSystemService(AppCompatActivity.NOTIFICATION_SERVICE) as NotificationManager
val notification = NotificationCompat.Builder(context, "TOTK").setContentText("about ${days}days, ${hours} hours left until TOTK's release").setContentTitle("time until tears of the kingdom").setSmallIcon(R.mipmap.ic_totk).build()
notificationManager.notify(1, notification)
}
}
}
清单文件
<?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.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name=".app"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_totk_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.TOKTTimer"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".SendNotification" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.DATE_CHANGED" />
</intent-filter>
</receiver>
</application>
</manifest>
我创建了通知渠道
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
class app: Application() {
override fun onCreate() {
super.onCreate()
val channel = NotificationChannel(
"TOTK",
"Time till TOKT",
NotificationManager.IMPORTANCE_HIGH
)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
1条答案
按热度按时间bmvo0sr51#
欢迎来到StackOverflow!
我通过在
reboot
之后启动Service
实现了类似的功能试试这个:
在
SendNotification
类中,启动一个Service
然后,按如下方式定义
MyBootService
:我的AndroidManifest.xml看起来像这样:
希望有帮助!
**P.S:**我以前用过Java,但你也可以用Kotlin写同样的东西:)