[Codelab学习]高级Android课程1.1 通知的使用

1.1使用Android通知

[Codelab学习]高级Android课程1.1 通知的使用_第1张图片
notifation

从GitHub克隆存储库,然后切换到start分支。

git clone https://github.com/googlecodelabs/android-kotlin-notifications
1.在Android Studio中打开并运行该应用。

您将看到一个鸡蛋图像和一个下拉菜单,其中列出了预煮鸡蛋的预定时间间隔。

单击三角形的 “软煮”下拉菜单。

列表中的第一个选项用于测试目的,并将警报设置为仅10秒。

列表旁边是一个开关,用于启动egg计时器。您可以随时使用此开关启动和停止Egg计时器。

入门代码具有完整的功能,这意味着您可以设置鸡蛋计时器,并观看它倒数为0。

计时器结束后,将显示一条吐司消息,如下所示。

2.检查源代码。

入门应用程序包含一个名为的活动MainActivity。有一个名为三个子包receiveruiutil

  • /receiver -The receiver包含两个名为广播接收机AlarmReceiverSnoozeReceiver。当用户定义的计时器AlarmReceiver启动时,由触发AlarmManager发送通知。SnoozeReceiver处理用户单击以暂停通知。
  • / ui-这包含EggTimerFragment作为应用程序UI部分的一部分。EggTimerViewModel负责启动和取消计时器以及其他与生命周期相关的应用程序任务。
  • / util-在此程序包中有两个文件。BindingUtils.kt具有绑定适配器来启用应用程序UI和的数据绑定ViewModelNotificationUtils.kt在上有扩展方法NotificationManager

代码架构 databinding ,livedata ,协程,viewmodel,倒计时控制显示和AlarmManagerCompat控制广播

核心代码

NotifationUtils.kt

package com.example.android.eggtimernotifications.util

import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import androidx.core.app.NotificationCompat
import com.example.android.eggtimernotifications.MainActivity
import com.example.android.eggtimernotifications.R
import com.example.android.eggtimernotifications.receiver.SnoozeReceiver

// Notification ID.
private val NOTIFICATION_ID = 0
private val REQUEST_CODE = 0
private val FLAGS = 0

// TODO: Step 1.1 extension function to send messages (GIVEN)
/**
 * Builds and delivers the notification.
 *
 * @param context, activity context.
 */
fun NotificationManager.sendNotification(messageBody: String, applicationContext: Context) {
    // Create the content intent for the notification, which launches
    // this activity
    //  Step 1.11 create intent 创建MainActivity意图
    val contentIntent = Intent(applicationContext, MainActivity::class.java)


    // Step 1.12 create PendingIntent 创建可传递意图
    val contentPendingIntent = PendingIntent.getActivity(
        applicationContext,
        NOTIFICATION_ID,
        contentIntent,
        PendingIntent.FLAG_UPDATE_CURRENT
    )

    //  Step 2.0 add style 添加Style

    val eggImage = BitmapFactory.decodeResource(
        applicationContext.resources,
        R.drawable.cooked_egg
    )
    //通知扩展时大图标消失
    val bigPictureStyle = NotificationCompat.BigPictureStyle()
        .bigPicture(eggImage)
        .bigLargeIcon(null)

    // Step 2.2 add snooze action 添加延后动作
    val snoozeIntent = Intent(applicationContext, SnoozeReceiver::class.java)
    val snoozePendingIntent = PendingIntent.getBroadcast(
        applicationContext,
        REQUEST_CODE,
        snoozeIntent,
        FLAGS
    )

    //  Step 1.2 get an instance of NotificationCompat.Builder 创建一个 NotificationCompat.Builder
    // Build the notification
    val builder = NotificationCompat.Builder(
        applicationContext,
        applicationContext.getString(R.string.egg_notification_channel_id)
    )

        //  Step 1.8 use the new 'breakfast' notification channel

        //  Step 1.3 set title, text and icon to builder 设置标题 内容 图标
        .setSmallIcon(R.drawable.cooked_egg)
        .setContentTitle(applicationContext.getString(R.string.notification_title))
        .setContentText(messageBody)

        //  Step 1.13 set content intent 添加点击内容的意图
        .setContentIntent(contentPendingIntent)
        .setAutoCancel(true)

        // Step 2.1 add style to builder 添加Style
        .setStyle(bigPictureStyle)
        .setLargeIcon(eggImage)

        // Step 2.3 add snooze action 添加延后动作
        .addAction(
            R.drawable.common_google_signin_btn_icon_dark,
            applicationContext.getString(R.string.snooze),
            snoozePendingIntent
        )

        //  Step 2.5 set priority 设置通知等级
        .setPriority(NotificationCompat.PRIORITY_HIGH)

    //  Step 1.4 call notify 显示通知
    notify(NOTIFICATION_ID, builder.build())

}

// Step 1.14 Cancel all notifications 取消所有的通知

fun NotificationManager.cancelNotifications() {
    cancelAll()
}

EggTimerFragment.kt

package com.example.android.eggtimernotifications.ui

import android.app.NotificationChannel
import android.app.NotificationManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import com.example.android.eggtimernotifications.R
import com.example.android.eggtimernotifications.databinding.FragmentEggTimerBinding
import com.google.firebase.messaging.FirebaseMessaging

class EggTimerFragment : Fragment() {

    private val TOPIC = "breakfast"

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val binding: FragmentEggTimerBinding = DataBindingUtil.inflate(
            inflater, R.layout.fragment_egg_timer, container, false
        )

        val viewModel = ViewModelProviders.of(this).get(EggTimerViewModel::class.java)

        binding.eggTimerViewModel = viewModel
        binding.lifecycleOwner = this.viewLifecycleOwner

        // TODO: Step 1.7 call create channel
        createChannel(
            getString(R.string.egg_notification_channel_id),
            getString(R.string.egg_notification_channel_name)
        )

        return binding.root
    }

    private fun createChannel(channelId: String, channelName: String) {
        // TODO: Step 1.6 START create a channel
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //作为最后一个参数,传递通知通道的重要性级别
            val notificationChannel =
                NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)

            notificationChannel.enableLights(true)
            notificationChannel.lightColor = Color.RED
            //震动
            notificationChannel.enableVibration(true)
            notificationChannel.description = "Time for breakfast"
            notificationChannel.setShowBadge(false)

            val notificationManager =
                requireActivity().getSystemService(NotificationManager::class.java)

            notificationManager?.createNotificationChannel(notificationChannel)
        }
        // TODO: Step 1.6 END create a channel

    }

    companion object {
        fun newInstance() = EggTimerFragment()
    }
}


总结

  • 使用NotificationManager类来创建,发送,更新和取消使用通知。
  • 将NotificationChannel对象与createNotificationChannel方法一起使用,以设置通知的通道。
  • 使用addAction()将快速操作添加到通知中。
  • 使用setShowBadge()启用或禁用徽章。
  • 使用从Notification.Style扩展的样式来设置通知的样式。
  • 使用NotificationChannel.setImportance()设置重要性级别

你可能感兴趣的:([Codelab学习]高级Android课程1.1 通知的使用)