Phone 屏幕锁定时振动

Phone vibrate with screen locked

我正在一个应用程序中(在 Studio 中)制作一个计时器,当计时器达到 0 时,它会振动。我想让 phone 在屏幕锁定时仍然振动。有什么建议吗?

这是我的主要内容 activity:

    EditText timerWrite;
    ImageButton power;
    ImageButton check;
    TextView minsLeft;
    CountDownTimer countDownTimer = null;

    Vibrator vibe;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_screen);
        vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);



    timerWrite = (EditText) findViewById(R.id.timerWrite);
    power = (ImageButton) findViewById(R.id.power);
    check = (ImageButton) findViewById(R.id.check);

    minsLeft = (TextView) findViewById(R.id.minsLeft);


    power.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            vibe.cancel();
            if(countDownTimer != null)
                countDownTimer.cancel();
            minsLeft.setText("stopped");
        }
        });


    check.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            vibe.cancel();
            if (countDownTimer != null)
                countDownTimer.cancel();
            String text = timerWrite.getText().toString();

                if (!text.equalsIgnoreCase("")) {
                    int mins = Integer.valueOf(text);

                    countDownTimer = new CountDownTimer(mins * 60000, 1000) {

                        @Override
                        public void onTick(long milliseconds) {
                            long minutes = milliseconds / 60000;
                            long seconds = (milliseconds / 1000) % 60;
                            minsLeft.setText(getString(R.string.minutes) + (int) (minutes) + "  seconds:" + (int) (seconds));

                        }

                        @Override
                        public void onFinish() {
                            minsLeft.setText("Are You OK?");
                            long[] pattern = {0, 1000, 2000, 100};
                            vibe.vibrate(pattern, 1);
                        }
                    }.start();
                }
            }

    });
}

谢谢!

那将超出 Activity 生命周期,因为它会进入 onPause()onStop() 因此你的 code/app 不会工作,你正在寻找的是将 运行 没有这些限制的服务。

https://developer.android.com/guide/components/services.html

干杯。