android - 如何在 Broadcast Receiver 的接收事件中使用倒数计时器?

标签 android broadcastreceiver

我创建了一个服务,当用户按下电源按钮 3 次时,应该启动 sos 服务。我需要以下要求 当它第一次收到捕获计数时等于 1。 当 count=1 时,计时器应启动 1 分钟。在 count =3 的那 1 分钟内,我的 sos 服务应该启动了。这该怎么做? 这个我试过了。

 public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) {
            Calendar cal = Calendar.getInstance();
            long time = cal.getTimeInMillis();
            String str = String.valueOf(time);
            str = str.substring(0,9);
            time = Long.parseLong(str);

            Long timestamp = pref.getLong("timestamp",0);
            int counter = pref.getInt("counter",0);
            if(timestamp != 0){
                if(time == timestamp){
                    counter++;
                    if(counter == 3){
                        editor.putInt("counter",0);
                        editor.putString("SOS","SOS OFF");
                        editor.putInt("SOS_Flag",0);    //for power button
                        Log.e("power button counter",String.valueOf(counter));
                        startService(new Intent(paramAnonymousContext, SosService.class));
                    }else{
                        editor.putInt("counter",counter);
                        editor.putLong("timestamp",time);
                    }
                }else{
                    editor.putLong("timestamp",time);
                    editor.putInt("counter",counter);
                }
            }else{
                editor.putLong("timestamp",time);
                editor.putInt("counter",counter);
            }
            editor.apply();

最佳答案

要启动一个计时器,你可以使用这样的东西:

new Handler().postDelayed(new Runnable() {
                    public void run() {
                        //send SOS if counter == 3
                    }
                }, 60000);

只需在 counter == 1 上开始这段代码。

关于android - 如何在 Broadcast Receiver 的接收事件中使用倒数计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33826454/

相关文章:

android - 在棉花糖中打开图像选择器时应用程序崩溃

android - 使用 ProgressDialog 和 AsyncTask 避免样板文件?

android - Google play 的搜索如何运作?

android - 广播接收器 onReceive() 被多次调用

android - 如何从 IntentService 返回一个对象?

Android 将数据从 Activity 传递到 BroadcastReceiver 显示 null

java - 如何在 android java 中使用插值获得类似的 tweenmax 效果?

android - Android WebView 缓存目录中的文件格式是什么(data_1、f_000001 等)?

android - 监控 Android 服务中的网络连接类型变化

android - 如何每天6点运行后台任务 :30PM