Andlua實現(xiàn)通知欄顯示

-- 導(dǎo)入需要用到的各種安卓類庫
require "import"
import "android.app.*"
import "android.os.*"
import "android.widget.*"
import "android.view.*"
import "android.content.Intent"
import "android.app.PendingIntent"
-- 在 onCreate 函數(shù)中創(chuàng)建應(yīng)用界面
function onCreate(savedInstanceState)
?-- 設(shè)置標題
?activity.setTitle("通知示例")
?-- 創(chuàng)建一個垂直方向的線性布局
?local layout = LinearLayout(activity)
?layout.setOrientation(LinearLayout.VERTICAL)
?-- 創(chuàng)建一個按鈕控件,并設(shè)置其文本
?local button = Button(activity)
?button.setText("顯示通知")
?-- 設(shè)置按鈕點擊事件
?button.setOnClickListener(View.OnClickListener{
??onClick = function(view)
???-- 獲取 NotificationManager 服務(wù)對象
???local notificationManager = activity.getSystemService(activity.NOTIFICATION_SERVICE)
???-- 如果設(shè)備版本大于等于 O,創(chuàng)建一個通知渠道
???if Build.VERSION.SDK_INT >= Build.VERSION_CODES.O then
????local channel = NotificationChannel("my_channel_01", "通知渠道名稱", NotificationManager.IMPORTANCE_DEFAULT)
????-- 設(shè)置通知渠道的行為屬性,包括是否震動、是否有聲音等
????notificationManager.createNotificationChannel(channel)
???end
???-- 創(chuàng)建一個 Intent,用于啟動一個新的 Activity 頁面
???local intent = Intent(activity, LuaActivity)
???intent.putExtra("message", "這是從通知啟動的 Activity。")
???-- 創(chuàng)建一個 PendingIntent 對象,用于在用戶點擊通知時打開該 Activity 并傳遞額外數(shù)據(jù)
???local pendingIntent = PendingIntent.getActivity(activity, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
???-- 創(chuàng)建一個 Notification.Builder 對象,用于構(gòu)造通知
???local notificationBuilder = Notification.Builder(activity)
???-- 設(shè)置通知標題、內(nèi)容、小圖標,并將 PendingIntent 對象關(guān)聯(lián)到通知中
???.setContentTitle("標題測試")
???.setContentText("這是一條通知消息。")
???.setSmallIcon(android.R.drawable.stat_notify_chat)
???-- 設(shè)置該通知為持久通知,不會在用戶下拉通知欄時被移除
???.setOngoing(true)
???.setContentIntent(pendingIntent)
???-- 如果設(shè)備版本大于等于 O,將該通知與剛才創(chuàng)建的通知渠道關(guān)聯(lián)
???if Build.VERSION.SDK_INT >= Build.VERSION_CODES.O then
????notificationBuilder.setChannelId("my_channel_01")
???end
???-- 使用 NotificationManager 發(fā)送該通知
???notificationManager.notify(1, notificationBuilder.build())
??end
?})
?-- 將按鈕添加到布局中
?layout.addView(button)
?-- 將布局設(shè)置為當前 Activity 的內(nèi)容視圖
?activity.setContentView(layout)
end
-- 在 onResume 函數(shù)中處理 Activity 進入前臺后的邏輯
function onResume()
?-- 獲取啟動 Activity 時傳遞的文本信息
?local message = activity.getIntent().getStringExtra("message")
?-- 如果文本信息不為空,使用 Toast 彈出提示框顯示該文本信息
?if message then
??Toast.makeText(activity, message, Toast.LENGTH_SHORT).show()
?end
end