Android setAlarmClock立即触发

问题描述

我创建了一个简单的应用程序来试用setAlarmClock()MainActivity中只有一个按钮,单击时会调用setAlarm

代码在下面。

MainActivity

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "alarmclock.MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void setAlarm(View view) {
        Context context = getApplicationContext();
        Intent intent = new Intent(context,AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getbroadcast(context,intent,0);

        long nextTrigger = SystemClock.elapsedRealtime()+10*1000;
        Log.i(TAG,SystemClock.elapsedRealtime() + ": scheduling next alarm at " + nextTrigger);

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        AlarmManager.AlarmClockInfo ac = new AlarmManager.AlarmClockInfo(nextTrigger,null);
        alarmManager.setAlarmClock(ac,pendingIntent);
    }
}

AlarmReceiver

public class AlarmReceiver extends broadcastReceiver {
    private static final String TAG = "alarmclock.AlarmReceiver";

    @Override
    public void onReceive(Context context,Intent intent) {
        Log.i(TAG,SystemClock.elapsedRealtime() + " in AlarmReceiver onReceive()");
    }
}

我基本上会在10秒后触发警报,但是由于某种原因,它会立即触发。

2020-09-21 22:09:56.664 17910-17910/com.example.alarmclock I/alarmclock.MainActivity: 3362358: scheduling next alarm at 3372358
2020-09-21 22:09:56.687 17910-17910/com.example.alarmclock I/alarmclock.AlarmReceiver: 3362382 in AlarmReceiver onReceive()

如果我使用setExactAndAllowWhileIdle,则相同的代码似乎可以正常工作。但是我特别想尝试setAlarmClock

解决方法

AlarmClockInfo需要一个挂牌时间:

从该时间段开始的墙壁时间(毫秒)内触发基本警报的时间

但是您正在使用Creating network "web_ecommerce_2019_default" with the default driver Building frontend Step 1/9 : FROM node:latest ---> 003358826bdb Step 2/9 : WORKDIR /usr/src/app ---> Using cache ---> b80128411a06 Step 3/9 : ENV DEBIAN_FRONTEND=noninteractive ---> Running in a4ad3ef0c8a0 Removing intermediate container a4ad3ef0c8a0 ---> 78a0d6ebe0aa Step 4/9 : ENV PATH /app/node_modules/.bin:$PATH ---> Running in 904c4a0bc568 Removing intermediate container 904c4a0bc568 ---> bbf5724bc6ed Step 5/9 : COPY package*.json ./ ---> b42de2577a71 Step 6/9 : RUN npm install ---> Running in cf82a0a54928 > [email protected] postinstall /usr/src/app/node_modules/core-js > node -e "try{require('./postinstall')}catch(e){}" Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library! The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: > https://opencollective.com/core-js > https://www.patreon.com/zloirock Also,the author of core-js ( https://github.com/zloirock ) is looking for a good job -) > @angular/[email protected] postinstall /usr/src/app/node_modules/@angular/cli > node ./bin/postinstall/script.js npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/webpack-dev-server/node_modules/fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"}) npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/watchpack-chokidar2/node_modules/fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"x64"}) npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"x64"}) added 1355 packages from 1121 contributors and audited 1360 packages in 35.503s 44 packages are looking for funding run `npm fund` for details found 5 vulnerabilities (3 low,2 high) run `npm audit fix` to fix them,or `npm audit` for details Removing intermediate container cf82a0a54928 ---> 66a77c23391d Step 7/9 : RUN npm install -g @angular/[email protected] ---> Running in f3faf59bdf90 npm WARN deprecated [email protected]: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies. npm WARN deprecated [email protected]: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2. npm WARN deprecated [email protected]: Please see https://github.com/lydell/urix#deprecated npm WARN deprecated [email protected]: https://github.com/lydell/resolve-url#deprecated /usr/local/bin/ng -> /usr/local/lib/node_modules/@angular/cli/bin/ng npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.2.2 (node_modules/@angular/cli/node_modules/chokidar/node_modules/fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"x64"}) + @angular/[email protected] added 290 packages from 180 contributors in 13.394s Removing intermediate container f3faf59bdf90 ---> 13a82ea9872f Step 8/9 : COPY . ./ ---> 4a60b6662c58 Step 9/9 : RUN ng serve --host 0.0.0.0 ---> Running in 7ece55d37214 WARNING: This is a simple server for use in testing or debugging Angular applications locally. It hasn't been reviewed for security issues. Binding this server to an open connection can result in compromising your application or computer. Using a different host than the one passed to the "--host" flag might result in websocket connection issues. You might need to use "--disableHostCheck" if that's the case. Compiling @angular/core : es2015 as esm2015 Compiling @angular/common : es2015 as esm2015 Compiling @angular/platform-browser : es2015 as esm2015 Compiling @angular/platform-browser-dynamic : es2015 as esm2015 Compiling @angular/router : es2015 as esm2015 chunk {main} main.js,main.js.map (main) 60.6 kB [initial] [rendered] chunk {polyfills} polyfills.js,polyfills.js.map (polyfills) 141 kB [initial] [rendered] chunk {runtime} runtime.js,runtime.js.map (runtime) 6.15 kB [entry] [rendered] chunk {styles} styles.js,styles.js.map (styles) 9.69 kB [initial] [rendered] chunk {vendor} vendor.js,vendor.js.map (vendor) 2.99 MB [initial] [rendered] Date: 2020-09-21T09:49:21.249Z - Hash: a0c3616136a93ab0d917 - Time: 29924ms ** Angular Live Development Server is listening on 0.0.0.0:4200,open your browser on http://localhost:4200/ ** : Compiled successfully. Date: 2020-09-21T09:49:22.371Z - Hash: a0c3616136a93ab0d917 5 unchanged chunks Time: 806ms : Compiled successfully. 时间,因此请使用public static String getRandomPassword(int count) { StringBuilder password = new StringBuilder(); for (int i = 0; i < count; i++) { switch (getRandomInteger(0,4)) { case 0: password.append((char) getRandomInteger(65,90)); break; case 1: password.append((char) getRandomInteger(97,122)); break; default: password.append(getRandomInteger(0,9)); break; } } return password.toString(); } public static int getRandomInteger(int minimum,int maximum) { return ((int) (Math.random() * (maximum - minimum))) + minimum; } 来解决问题。

,

在我从SystemClock.elapsedRealtime()更改为System.currentTimeMillis()之后,它起作用了。

long nextTrigger = System.currentTimeMillis()+10*1000

详细阅读了documentation之后,我意识到AlarmClockInfo构造函数的第一个参数采用

long:墙上时间触发基本警报的时间 自纪元以来的毫秒数

这是System.currentTimeMillis()所提供的。

另一方面,SystemClock.elapsedRealtime()返回

自系统启动以来的时间...

自纪元以来,它将始终比挂历时间小得多。结果,警报立即得到安排,因为

如果指定的触发时间已过去,警报将立即触发。