Android 8.0以后android得权限有所更改,但是影响录屏得得权限目前只影响Android Q版本,具体原理请看下面这篇博客,是他人所写,很是详细。
https://blog.csdn.net/sinat_20059415/article/details/80584487
下面具体写适配流程:
1.先在AndroidManifest.xml文件里面添加权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
2.修改Service得清单
<service
android:name=".ScreenRecordService"
android:enabled="true"
android:exported="true"
tools:targetApi="q"
android:foregroundServiceType="mediaProjection" />
3.修改目标编译版本29降为28
4.修改开启Service得代码
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startActivity(intent);
}
5.因为权限更改,Android不允许后台程序在用户不知情得情况执行操作,所以必须在5s内执行startForeground(),否则会出现异常。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
createNotificationChannel();
}
}
private void createNotificationChannel() {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 通知渠道的id
String id = "my_channel_01";
// 用户可以看到的通知渠道的名字.
CharSequence name = getString(R.string.app_name);
// 用户可以看到的通知渠道的描述
String description = "描述描述";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = null;
mChannel = new NotificationChannel(id, name, importance);
// 配置通知渠道的属性
mChannel.setDescription(description);
// 设置通知出现时的闪灯(如果 android 设备支持的话)
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
// 设置通知出现时的震动(如果 android 设备支持的话)
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
// 最后在notificationmanager中创建该通知渠道 //
mNotificationManager.createNotificationChannel(mChannel);
// 为该通知设置一个id
int notifyID = 1;
// 通知渠道的id
String CHANNEL_ID = "my_channel_01";
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(this)
.setContentTitle(getString(R.string.vip_dialog_title_text)) .setContentText(name + "正在录制屏幕内容...")
.setSmallIcon(R.mipmap.ic_logo)
.setChannelId(CHANNEL_ID)
.build();
startForeground(1,notification);
}
6.在停止Service得时候,也有记得执行stopForeground()停止该服务
@Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
}
至此适配结束。
记一个用Android10模拟器调试时出现问题得解决方法:
// 解决 native libraries 不支持cpu的体系结构。允许模拟器调试
splits {
abi {
enable true
reset()
include 'x86', 'armeabi-v7a','x86_64'
universalApk true
}
}