我正在开发一个具有后台服务的录像机应用程序。我得到了这些错误:
java.lang.RuntimeException: Unable to start service com.example.justbackgroundcamera.BackgroundVideoRecorder@82e8d33 with Intent { cmp=com.example.justbackgroundcamera/.BackgroundVideoRecorder (has extras) }: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@959f86d -- permission denied for window type 2003
代码:
windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
surfaceView = new SurfaceView(this);
ViewGroup.LayoutParams layoutParams = new WindowManager.LayoutParams(1, 1,
Build.VERSION.SDK_INT < Build.VERSION_CODES.O ?
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT :
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
// layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
windowManager.addView(surfaceView, layoutParams);
surfaceView.getHolder().addCallback(this);
清单:
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
我认为有一些关于权限的错误。如何获取这些权限?
发布于 2019-10-31 09:36:27
我已经解决了问题。当使用Android M或更高版本时,我们需要一些权限。您可以使用“覆盖其他应用程序”权限来解决此问题。
添加到清单
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
WindowManager
windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
surfaceView = new SurfaceView(this);
ViewGroup.LayoutParams layoutParams = new WindowManager.LayoutParams(1, 1,
Build.VERSION.SDK_INT < Build.VERSION_CODES.O ?
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY :
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
windowManager.addView(surfaceView, layoutParams);
surfaceView.getHolder().addCallback(this);
添加到代码中(onCreate)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 0);
}
}
发布于 2019-10-30 20:14:17
信息太少了。因此,请确保您的应用程序支持对Android >= O的限制。因为在这种情况下,您无法在没有通知和startForeground
调用的情况下在后台启动Service
。
对于ex。
final NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
final String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? getNotificationChannel(manager) : "";
final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
final Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.build();
startForeground(110, notification);
https://stackoverflow.com/questions/58632930
复制