Android通知Notification
通知(notification)是Android系统的一个功能,当某个应用程序希望向用户提示一些信息,而应用不在前台运行,就可以借助通知实现,当发出一条通知后,手机最上方的状态栏会显示一个通知的按钮,下拉状态栏可以看到通知的内容。
MainActivity
package com.sunnyweather.notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.app.NotificationCompat
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 建立通知管理者
val manager = getSystemService(Context.NOTIFICATION_SERVICE)as NotificationManager
// 建立渠道normal,这里要进行Android版本的判断
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val channel = NotificationChannel("normal","Normal",NotificationManager.IMPORTANCE_DEFAULT)
manager.createNotificationChannel(channel)
}
// 设置点击事件
sendDefaultNotice.setOnClickListener{
// 构建点击通知消息后的响应
val intent = Intent(this,NotificationActivity::class.java)
val pi = PendingIntent.getActivity(this,0,intent,0)
// 构建通知消息,消息对应渠道normal
val notification = NotificationCompat.Builder(this,"normal")
.setContentTitle("This is content title")
.setContentText("This is content text")
.setSmallIcon(R.drawable.ic_launcher_background)
.setLargeIcon(BitmapFactory.decodeResource(resources,R.drawable.ic_launcher_foreground))
.setContentIntent(pi)
.setAutoCancel(true)
.build()
manager.notify(1,notification)
}
}
}
NotificationActivity
package com.sunnyweather.notification
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class NotificationActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_notification)
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/sendDefaultNotice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Notice">
</Button>
</LinearLayout>
activity_notification.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="50dp"
android:text="Hello!This is notification layout">
</TextView>
</RelativeLayout>
结果
点击SEND NOTICE按钮,会显示通知消息,然后点击通知消息进入一个新页面