Как сделать снимок с помощью сервиса переднего плана в Android Oreo - PullRequest
0 голосов
/ 20 октября 2018

Я пытаюсь сделать снимок с камеры без предварительного просмотра и пользуюсь сервисом, потому что он мне нужен, чтобы сделать снимок без открытия какого-либо пользовательского интерфейса.Я использую android-hidden-camera , и она прекрасно работает в API <26, но, начиная с Oreo, она работает, но останавливает интерфейс во время работы службы, примерно на 3 секунды. </p>

это код, который я использую:

public class BackService extends HiddenCameraService {


private void toast(String msg) {
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}

private class DoInBackground extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        BackService.this.takePicture();
        return "Captured";
    }

    @Override
    protected void onPreExecute() {   }

    @Override
    protected void onProgressUpdate(Void... values) {}

    @Override
    protected void onPostExecute(String result) {   }


}

@Override
public void onCreate() {
    createNotification();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {


    if (ContextCompat.checkSelfPermission(this, "android.permission.CAMERA") != 0) {
        toast("Camera permission not granted");
    } else if (HiddenCameraUtils.canOverDrawOtherApps(this)) {
        startCamera(new CameraConfig().getBuilder(getApplicationContext())
                .setCameraFacing(CameraFacing.REAR_FACING_CAMERA)
                .setCameraResolution(CameraResolution.MEDIUM_RESOLUTION)
                .setImageFormat(CameraImageFormat.FORMAT_JPEG)
                .setImageRotation(CameraRotation.ROTATION_270)
                .build());

        new DoInBackground().execute("");
    } else {
        HiddenCameraUtils.openDrawOverPermissionSetting(this);
    }


    return START_NOT_STICKY;
}


@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onImageCapture(File imageFile) {
    toast(imageFile.getAbsolutePath());
    System.out.println("FULL PATH: "+imageFile.getAbsolutePath());
    stopForeground(true);
    stopSelf();

}

@Override
public void onCameraError(int errorCode) {
    toast("onCameraError() called");
    switch (errorCode) {
        case CameraError.ERROR_CAMERA_OPEN_FAILED:
            toast("CANNOT OPEN CAMERA");
            break;
        case CameraError.ERROR_IMAGE_WRITE_FAILED:
            toast( "EXT STORAGE PERM FALSE");
            break;
        case CameraError.ERROR_CAMERA_PERMISSION_NOT_AVAILABLE:
            toast("CAMERA PERMISSION FALSE");
            break;
        case CameraError.ERROR_DOES_NOT_HAVE_OVERDRAW_PERMISSION:
            toast("OVERDRAW PERMISSIONS FALSE");
            HiddenCameraUtils.openDrawOverPermissionSetting(this);
            break;
        case CameraError.ERROR_DOES_NOT_HAVE_FRONT_CAMERA:
            toast("Your device does not have front camera.");
            break;
    }
}


private void createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = Constants.CHANNEL_NAME;
        String description = Constants.NOTIFICATION_TEXT;
        int importance = NotificationManager.IMPORTANCE_LOW;
        NotificationChannel channel = new NotificationChannel(Constants.NOTIF_CHANNEL_ID, name, importance);
        channel.setDescription(description);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}


private void createNotification(){
    createNotificationChannel();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        Notification.Builder builder = new Notification.Builder(this, Constants.NOTIF_CHANNEL_ID)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(Constants.NOTIFICATION_TEXT)
                .setAutoCancel(true);

        Notification notification = builder.build();
        startForeground(1, notification);

    } else {

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(Constants.NOTIFICATION_TEXT)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setAutoCancel(true);

        Notification notification = builder.build();
        startForeground(1, notification);
    }
}

startCamera () - это тот, который занимает время, чтобы закончить, и мне нужно поспать не менее 1 секунды перед выполнением takePicture ()

...