Android 8.0 悬浮框和service适配

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/c_he_n/article/details/83547456

背景

在项目中,需要启动一个播放音乐的service,恰巧又是一个悬浮的,每次播放几秒钟就无缘无故的消失了,Android 8.0 本身做了限制,于似乎就去Google啊 。Google后Google 对Android 8.0的后台做了限制,主要处于性能的考虑,悬浮框和service启动会有问题,正好项目中需要需要适配。具体限制看google后台限制

悬浮框

从Android的api中看出,在26时TYPE_TOAST由TYPE_APPLICATION_OVERLAY替代了,所以需要在Android 8.0中可以进行下面的适配。
API描述

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
	mAudioParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
	mAudioParams.type = WindowManager.LayoutParams.TYPE_TOAST;
}

service

在启动service时,需要采用startForegroundService,Google不允许在后台启动service,除非你让用户知道。

if (Build.VERSION.SDK_INT >= 26) {
            mContext.startForegroundService(audioIntent);
        } else {
            mContext.startService(audioIntent);
        }

在系统创建服务后,应用有五秒的时间来调用该服务的 startForeground() 方法以显示新服务的用户可见通知。在service类中的onStartCommand中调用。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			Notification.Builder builder = new Notification.Builder(this, "555").setContentTitle(getString(R.string.app_name)).setContentText("SmartTracker Running").setAutoCancel(true);
			Notification notification = builder.build();
			startForeground(1, notification);
		}

以上代码可以解决上面两个问题,还有一点就是悬浮框的权限记得开下,不然看不到效果哦。

猜你喜欢

转载自blog.csdn.net/c_he_n/article/details/83547456
今日推荐