Android Kotlin - 每分钟发送通知

时间:2017-06-26 15:28:06

标签: android kotlin

我正在尝试每分钟向用户发送一个通知(仅用于测试目的)。这就是我到目前为止所做的:

class AlertReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent){
        sendNotification(context, "Sample", "Notification sent....")
    }

    fun sendNotification(context: Context, title: String, body: String){
        val notification = NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.notification_icon_background)
                .setContentTitle(title)
                .setContentText(body)

        val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, Intent(context, TimerService::class.java), 0)

        notification.setContentIntent(pendingIntent)
        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(1, notification.build())
    }
}

class TimerService : Service() {

    override fun onCreate(){
        toast("Activity Created")
        setAlarm()
        super.onCreate()
    }

    override fun onDestroy(){
        super.onDestroy()
        toast("Stopped activity")
    }

    fun setAlarm(){

        val alertTime: Long = GregorianCalendar().timeInMillis+5*1000
        val alertIntent: Intent = Intent(this, AlertReceiver::class.java)

        val manager: AlarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        manager.set(AlarmManager.RTC_WAKEUP, alertTime, PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT))
    }

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

这是我的AndroidManifest.xml:

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.NoActionBar">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".TimerActivity">
            <intent-filter>
                <action android:name="com.example.user.luciddream.TimerActivity" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <service android:name=".TimerService"></service>
        <receiver android:name=".AlertReceiver"></receiver>
    </application>

</manifest>

使用manager.set工作正常。但是这样,显然它只会等待一次,最后发出通知。但是,我似乎无法使用manager.setRepeating()

在这种情况下,manager.setRepeating()代码应如何显示?

由于

1 个答案:

答案 0 :(得分:0)

你可以这样做:

定义NotificationUtil.kt为Android O及以上版本创建Channels

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.ContextWrapper
import android.graphics.Color
import android.os.Build
import android.support.annotation.RequiresApi

@RequiresApi(Build.VERSION_CODES.O)
class NotificationUtils(base: Context) : ContextWrapper(base) {

    val nManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    init {
        createChannels()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun createChannels() {
        val myChannel = NotificationChannel(CHANNEL_ID,
                CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT).apply {
            enableLights(true)
            enableVibration(true)
            lightColor = Color.GREEN
            lockscreenVisibility = Notification.VISIBILITY_PRIVATE
        }

        nManager.createNotificationChannel(myChannel)
    }

    companion object {
        const val CHANNEL_ID = "my.app.CHANNEL_ID"
        const val CHANNEL_NAME = "my.app.Notification"
    }
}

创建notificationService.kt来处理通知:

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.RingtoneManager
import android.os.Build
import android.os.IBinder
import oryx.kortex.locateme.R
import android.provider.Telephony



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

    override fun onCreate() {
        val context = this as Context
        }

        override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {

        val defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(this) 
        val intent = Intent(Intent.ACTION_MAIN)
        intent.`package` = defaultSmsPackageName

        val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0)

        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

        val mNotificationId: Int = 1000

        val nManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val mNotification = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                    Notification.Builder(context, CHANNEL_ID)
                                } else {
                                   Notification.Builder(context)
                                }.apply {
                                    setContentIntent(pendingIntent)
                                    setSmallIcon(R.drawable.ic_error_black_24dp)
                                    setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher))
                                    setAutoCancel(true)
                                    setContentTitle("Title")
                                    setStyle(Notification.BigTextStyle().bigText("message"))
                                    setContentText("MESSAGE")
                                }.build()

                nManager.notify(mNotificationId, mNotification)
        return Service.START_STICKY
    }

    companion object {
        const val CHANNEL_ID = "my.app.CHANNEL_ID"
    }
}

MainActivity.kt中确保调用Util来创建频道:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)  NotificationUtils(this)

在broadCastRciever中,定义服务并调用它:

val notificationService = Intent(context, NotificationService::class.java)

context.startService(notificationService)

确保在manifest

中定义所需内容
<service android:name=".Services.NotificationService" />
<receiver android:name=".broadcasts.xxxx">
    <intent-filter>
        <action android:name="android.intent.action.xxx" />
    </intent-filter>
</receiver>