桌面部件需要开启服务请求后台数据,刷新桌面部件view
//权限申请
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
//开启服务 android8.0开启和不在前台进程中
val intentService = Intent(context, xxxService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !AppUtils.isAppForeground()) {
context?.startForegroundService(intentService)
} else {
context?.startService(intentService)
}
//
class xxxxService : Service() {
...
override fun onCreate() {
super.onCreate()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !AppUtils.isAppForeground()) {
val builder = NotificationBuilder(this)
val notification = builder.buildNotification()
startForeground(NotificationBuilder.NOTIFICATION_ID, notification)
}
}
....
}
//
<service android:name=".widget.s6.service.xxxxService"
android:exported="false">
<intent-filter>
<action android:name="com.xxxx.xxxx.xxx"/>
</intent-filter>
</service>
//
class NotificationBuilder(private val mContext: Context) {
private val mNotificationManager: NotificationManager
fun buildNotification(): Notification {
if (shouldCreateNowPlayingChannel()) {
createNowPlayingChannel()
}
val builder = NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
return builder.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("xxxxtitle")
.setOnlyAlertOnce(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build()
}
@RequiresApi(api = Build.VERSION_CODES.O)
private fun nowPlayingChannelExists(): Boolean {
return mNotificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID) != null
}
private fun shouldCreateNowPlayingChannel(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !nowPlayingChannelExists()
}
@RequiresApi(api = Build.VERSION_CODES.O)
private fun createNowPlayingChannel() {
val channel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
"当前播放",
NotificationManager.IMPORTANCE_LOW
)
channel.description &