Service管理通知栏通知模板

代码:

Manifest:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

<application
...
<!--notice-->
<activity android:name=".notice.NoticeActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".notice.NoticeOtherActivity" />

<service
android:name=".notice.NoticeService"
android:enabled="true" />

</application>

Kotlin:
​​​NoticeActivity:​

class NoticeActivity: AppCompatActivity() {
private lateinit var noticeBinding: ActivityNoticeBinding

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
noticeBinding= ActivityNoticeBinding.inflate(layoutInflater)
setContentView(noticeBinding.root)

noticeBinding.messageSend.setOnClickListener {
val intent=Intent(this,NoticeService::class.java)
startService(intent)
}
}

}

​NoticeOtherActivity:​

class NoticeOtherActivity: AppCompatActivity() {
private lateinit var noticeOtherBinding: ActivityNoticeOtherBinding

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
noticeOtherBinding=ActivityNoticeOtherBinding.inflate(layoutInflater)
setContentView(noticeOtherBinding.root)

noticeOtherBinding.noticeOtherCloseService.setOnClickListener {
val intent=Intent(this,NoticeService::class.java)
stopService(intent)
}
}
}

​NoticeService:​

class NoticeService : Service() {
private val mBinder = MyBinder()

class MyBinder : Binder() {

}

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

override fun onCreate() {
super.onCreate()

val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
"my_service",
"前台Service通知",
NotificationManager.IMPORTANCE_DEFAULT
)
manager.createNotificationChannel(channel)
}

val intent = Intent(this, NoticeOtherActivity::class.java)
val pi = PendingIntent.getActivity(this, 0, intent, 0)
val notification = NotificationCompat.Builder(this, "my_service")
.setContentTitle("This is title")
.setContentText("This is content text")
.setSmallIcon(R.drawable.ic_launcher_background)
.setLargeIcon(
BitmapFactory.decodeResource(
resources,
R.drawable.ic_launcher_background
)
)
.setContentIntent(pi)
.build()
startForeground(1, notification)
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return super.onStartCommand(intent, flags, startId)
}

override fun onDestroy() {
super.onDestroy()
}
}

效果:

【Android】Service管理通知栏通知模板_安卓
【Android】Service管理通知栏通知模板_ide_02
【Android】Service管理通知栏通知模板_java_03
【Android】Service管理通知栏通知模板_ide_04