如何在Android9中使用后台服务

问题描述 投票:0回答:1

为什么不帮助任何人?

在我的应用程序中,我想开发屏幕录像机,为此,我使用service。在我的service中,我有一个按钮,当单击此按钮时,停止此service,然后打开我的activities。我编写以下代码并为我工作,但是在Android 9中,当单击停止按钮时,关闭了我的应用程序(service),但没有打开我的activity!我添加了FireBase crashlytics,但是对于此问题,不向我发送任何问题!我认为这个问题仅用于Android9

我的录音机服务等级代码:

public class FloatingLayoutService extends Service implements StepperFormListener {

    private WindowManager windowManager;
    private ConstraintLayout floatingLayout, floatingLay_root, floatingLay_main;
    private IBinder binder = new ServiceBinder();
    private LinearLayout floatingLay_headerLay, floatingLay_emptyStepLay;
    private ImageView floatingLay_pauseImg, floatingLay_goneImg, floatingLay_emptyImg;
    private Chronometer chronometer;
    private TextView floatingLay_tasksTxt, floatingLay_infoTxt, floatingLay_infoContentTxt, floatingLay_infoContentNextPage,
            floatingLay_emptyStepFinish;
    private RelativeLayout floatingLay_content, floatingLay_step2ContentLay;
    private VerticalStepperFormView floatingLay_stepper;
    private ScrollView floatingLay_infoContentScroll;
    private List<Step> steps = new ArrayList();
    private List<Integer> intList = new ArrayList<>();
    private List<TestStepsListResponse.Datum> testPlans = new ArrayList<>();
    private StringBuilder stringBuilder;
    //private WatermarkService watermarkService;
    private boolean isBound = false;
    private LayoutInflater layoutInflater;
    //Timer
    private boolean running;
    private int stepIndex = 1;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        //Inflate the layout using LayoutInflater
        layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        floatingLayout = (ConstraintLayout) layoutInflater.inflate(R.layout.service_floating_layout, null);
        //Init views
        stringBuilder = new StringBuilder();
        floatingLay_root = floatingLayout.findViewById(R.id.floatingLay_root);
        floatingLay_main = floatingLayout.findViewById(R.id.floatingLay_main);
        floatingLay_emptyImg = floatingLayout.findViewById(R.id.floatingLay_emptyImg);
        floatingLay_headerLay = floatingLayout.findViewById(R.id.floatingLay_headerLay);
        floatingLay_pauseImg = floatingLay_headerLay.findViewById(R.id.floatingLay_pauseImg);
        floatingLay_goneImg = floatingLay_headerLay.findViewById(R.id.floatingLay_goneImg);
        chronometer = floatingLay_headerLay.findViewById(R.id.floatingLay_timerTxt);
        floatingLay_tasksTxt = floatingLay_headerLay.findViewById(R.id.floatingLay_tasksTxt);
        floatingLay_infoTxt = floatingLay_headerLay.findViewById(R.id.floatingLay_infoTxt);
        floatingLay_content = floatingLayout.findViewById(R.id.floatingLay_content);
        floatingLay_stepper = floatingLay_content.findViewById(R.id.floatingLay_stepper);
        floatingLay_emptyStepLay = floatingLay_content.findViewById(R.id.floatingLay_emptyStepLay);
        floatingLay_step2ContentLay = floatingLay_content.findViewById(R.id.floatingLay_step2ContentLay);
        floatingLay_emptyStepFinish = floatingLay_content.findViewById(R.id.floatingLay_emptyStepFinish);
        floatingLay_infoContentTxt = floatingLay_content.findViewById(R.id.floatingLay_infoContentTxt);
        floatingLay_infoContentNextPage = floatingLay_content.findViewById(R.id.floatingLay_infoContentNextPage);
        floatingLay_infoContentScroll = floatingLay_content.findViewById(R.id.floatingLay_infoContentScroll);

        //Set layout params to display the controls over any screen.
        int LAYOUT_FLAG;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
        }
        final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                LAYOUT_FLAG,
                0,
                PixelFormat.TRANSLUCENT);
        // From API26, TYPE_PHONE deprecated. Use TYPE_APPLICATION_OVERLAY for O
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
            params.type = WindowManager.LayoutParams.TYPE_PHONE;
        //Initial position of the floating controls
        params.gravity = Gravity.BOTTOM | Gravity.START;
        params.x = 0;
        params.y = 0;
        //Add the controls view to windowManager
        windowManager.addView(floatingLayout, params);
        //Start timer
        timerMethod();
        //Stop service
        floatingLay_goneImg.setOnClickListener(v -> toggleLay(false));
        //Header layout
        if (stepIndex == 1) {
            changeHeaderLayouts(INFO);
            stepIndex = 2;
        } else {
            changeHeaderLayouts(TASKS);
        }
        //Change layouts
        floatingLay_infoTxt.setOnClickListener(v -> changeHeaderLayouts(INFO));
        floatingLay_tasksTxt.setOnClickListener(v -> changeHeaderLayouts(TASKS));
        //Click
        floatingLay_emptyImg.setOnClickListener(v -> toggleLay(false));
        //Get scenario
        floatingLay_infoContentTxt.setText(Html.fromHtml(App.testScenario));
        //Steps
        if (App.testPlansList.size() > 0) {
            floatingLay_stepper.setVisibility(View.VISIBLE);
            floatingLay_emptyStepLay.setVisibility(View.GONE);

            testPlans = App.testPlansList;
            for (int i = 0; i < testPlans.size(); i++) {
                if (testPlans.get(i).getItemType().equals(ConstKeys.TEST_STEP_TEXT_RESPONSE)) {
                    StepDynamicEdt stepDynamicEdt = new StepDynamicEdt(testPlans.get(i).getTitle(), testPlans.get(i).getDesc());
                    // add to list
                    steps.add(stepDynamicEdt);
                    intList.add(i);
                } else {
                    StepDynamicTxt stepDynamicTxt = new StepDynamicTxt(testPlans.get(i).getTitle(), testPlans.get(i).getDesc());
                    // add to list
                    steps.add(stepDynamicTxt);
                }
            }
            //Setup steps
            floatingLay_stepper.setup(this, steps)
                    .allowNonLinearNavigation(false)
                    .displayCancelButtonInLastStep(false)
                    .displayBottomNavigation(false)
                    .confirmationStepTitle("Accept")
                    .stepNextButtonText("Next")
                    .lastStepNextButtonText("Finish")
                    .includeConfirmationStep(false)
                    .init();
        } else {
            floatingLay_stepper.setVisibility(View.GONE);
            floatingLay_emptyStepLay.setVisibility(View.VISIBLE);

            floatingLay_emptyStepFinish.setOnClickListener(v -> {
                this.stopSelf();
                //Provide an haptic feedback on button press
                Vibrator vibrate = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
                Objects.requireNonNull(vibrate).vibrate(300);

                stopScreenSharing();

                Intent intent2 = new Intent(this, CompressorUploadActivity.class);
                intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent2);
            });
        }
        //Task page btn
        floatingLay_infoContentNextPage.setOnClickListener(v -> changeHeaderLayouts(TASKS));

        return START_STICKY;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        int orientation = newConfig.orientation;
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            floatingLay_content.getLayoutParams().height = (int) getResources().getDimension(R.dimen._350mdp);
            floatingLay_content.requestLayout();

        } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            floatingLay_content.getLayoutParams().height = (int) getResources().getDimension(R.dimen._180mdp);
            floatingLay_content.requestLayout();
        }
    }

    private void timerMethod() {
        chronometer.setFormat("%s");
        chronometer.setBase(SystemClock.elapsedRealtime());

        chronometer.setOnChronometerTickListener(chronometer -> {
            if ((SystemClock.elapsedRealtime() - chronometer.getBase()) >= 10000000) {
                chronometer.setBase(SystemClock.elapsedRealtime());
            }
        });

        if (!running) {
            chronometer.setBase(SystemClock.elapsedRealtime());
            chronometer.start();
            running = true;
        }
    }

    public void toggleLay(boolean isOpen) {
        if (!isOpen) {
            YoYo.with(Techniques.SlideOutDown)
                    .duration(500)
                    .withListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationStart(Animator animation) {
                            floatingLay_emptyImg.setVisibility(View.GONE);
                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            floatingLay_main.setVisibility(View.GONE);
                        }
                    })
                    .playOn(floatingLay_root);
        } else {
            YoYo.with(Techniques.SlideInUp)
                    .duration(500)
                    .withListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationStart(Animator animation) {
                            floatingLay_main.setVisibility(View.VISIBLE);
                            changeHeaderLayouts(TASKS);
                            new Handler().postDelayed(() -> floatingLay_emptyImg.setVisibility(View.VISIBLE), 200);
                        }
                    })
                    .playOn(floatingLay_root);
        }
    }

    private void changeHeaderLayouts(String type) {
        switch (type) {
            case INFO:
                floatingLay_infoTxt.setBackgroundColor(ContextCompat.getColor(this, android.R.color.white));
                floatingLay_tasksTxt.setBackgroundColor(ContextCompat.getColor(this, R.color.grayColor));
                floatingLay_infoContentScroll.setVisibility(View.VISIBLE);
                floatingLay_step2ContentLay.setVisibility(View.GONE);
                break;
            case TASKS:
                floatingLay_tasksTxt.setBackgroundColor(ContextCompat.getColor(this, android.R.color.white));
                floatingLay_infoTxt.setBackgroundColor(ContextCompat.getColor(this, R.color.grayColor));
                floatingLay_infoContentScroll.setVisibility(View.GONE);
                floatingLay_step2ContentLay.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onDestroy() {
        if (floatingLayout != null) windowManager.removeView(floatingLayout);
        super.onDestroy();
    }

    //Return ServiceBinder instance on successful binding
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    //Stop the service once the service is unbinded from recording service
    @Override
    public boolean onUnbind(Intent intent) {
        stopSelf();
        return super.onUnbind(intent);
    }

    @Override
    public void onCompletedForm() {
        this.stopSelf();
        App.stepsBodyList.clear();
        //Get data
        for (int i : intList) {
            stringBuilder.append("ID : ").append(testPlans.get(i).getId())
                    .append("Type : ").append(testPlans.get(i).getItemType())
                    .append("Content").append(steps.get(i).getStepData().toString()).append("-");
            App.stepsBodyList.add(new DataItem(testPlans.get(i).getId(),
                    testPlans.get(i).getItemType(),
                    steps.get(i).getStepData().toString()));
        }

        //Provide an haptic feedback on button press
        Vibrator vibrate = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
        Objects.requireNonNull(vibrate).vibrate(300);

        //Settings.System.putInt(this.getContentResolver(), "show_touches", 0);

        stopScreenSharing();

        Intent intent = new Intent(this, CompressorUploadActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onCancelledForm() {

    }

    public class ServiceBinder extends Binder {
        public FloatingLayoutService getService() {
            return FloatingLayoutService.this;
        }
    }

    /**
     * Set stop intent and start the recording service
     */
    private void stopScreenSharing() {
        Intent stopIntent = new Intent(this, RecorderService.class);
        stopIntent.setAction(ConstKeys.SCREEN_RECORDING_STOP);
        startService(stopIntent);
    }
}

单击完成按钮时,请拨打以下代码:

    floatingLay_emptyStepFinish.setOnClickListener(v -> {
        this.stopSelf();
        //Provide an haptic feedback on button press
        Vibrator vibrate = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
        Objects.requireNonNull(vibrate).vibrate(300);

        stopScreenSharing();

        Intent intent2 = new Intent(this, CompressorUploadActivity.class);
        intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent2);
    });

如何为Android 9修复此问题?

java android service android-service android-9.0-pie
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.