Android 8.0(Oreo)版本适配指南
通知
Android 8.0引入了通知渠道(Notification Channels)概念,使用户可以对不同类型的通知进行管理和定制。每个通知必须分配到一个渠道。
适配措施
在应用启动时创建通知渠道,并为每个通知指定渠道ID。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "my_channel_id"
val channelName = "My Channel"
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(channelId, channelName, importance)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
val notification = NotificationCompat.Builder(this, "my_channel_id")
.setContentTitle("Title")
.setContentText("Content")
.setSmallIcon(R.drawable.notification_icon)
.build()
notificationManager.notify(1, notification)
后台执行限制
Android 8.0对后台服务和广播进行了更严格的限制,以提高电池寿命和系统性能。
适配措施
- JobScheduler:使用
JobScheduler
来代替传统的后台服务,确保任务在系统资源可用时运行,并且不会过度消耗电池。
val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
val jobInfo = JobInfo.Builder(1, ComponentName(this, MyJobService::class.java))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setRequiresCharging(false)
.build()
jobScheduler.schedule(jobInfo)
- 广播接收器:使用显式广播代替隐式广播。隐式广播在后台运行时受到限制,因此显式广播是更好的选择。
后台位置限制
为了降低功耗,Android 8.0会限制应用在后台运行时检索用户当前位置的频率,每小时只能接收几次位置信息更新。
安装未知来源APK
Android 8.0移除了全局的“允许未知来源”设置,改为每个应用单独管理。
适配措施
- 请求权限:在
AndroidManifest.xml
中添加安装未知来源应用的权限。
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
- 引导用户授予权限:在应用需要安装未知来源APK时,引导用户到设置页面授予权限。
private void downloadAPK(){
boolean hasInstallPermission=getPackageManager().canRequestPackageInstalls();
if(hasInstallPermission){
// 安装应用的逻辑
}else{
// 跳转至“安装未知应用”权限界面,引导用户开启权限
Intent intent=new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
startActivityForResult(intent,REQUEST_CODE_UNKNOWN_APP);
}
}
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(requestCode==REQUEST_CODE_UNKNOWN_APP){
downloadAPK();
}
}