如何判断 Android 重复闹钟的年龄?

发布于 2024-11-30 05:57:10 字数 2042 浏览 1 评论 0原文

我安排了一个 setRepeating() 警报,如果它达到一定年龄,我想在它的 BroadcastReceiver 中禁用它。我宁愿在 BroadcastReceiver 内部禁用它,所以如果可能的话,这将是我的第一选择。

在我的 Activity 中:

// Start our alarm
Intent intent = new Intent(Main.this, Receiver.class);

long firstTime = SystemClock.elapsedRealtime();
firstTime += 2 * 1000; // start in 2 seconds
long interval = 2000; // 2 seconds for testing

intent.putExtra("start", firstTime); // Tell the receiver the creation date (not working)

PendingIntent sender = PendingIntent.getBroadcast(Main.this, 0, intent, 0);

// Schedule the alarm!
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, interval, sender);

在我的 BroadcastReceiver 中:

@Override
public void onReceive(Context context, Intent intent) {
    // ... alarm stuff
    long now = SystemClock.elapsedRealtime();
    Log.i("", "Alarm Running for " + (now - intent.getLongExtra("start", now)));
    //getLongExtra() defaults to 'now' because there is no extra 'start'
}

在 LogCat 中,我看到了这个。

08-19 11:01:04.420: INFO/(1371): Alarm Running for 0
08-19 11:01:06.420: INFO/(1371): Alarm Running for 0
08-19 11:01:08.430: INFO/(1371): Alarm Running for 0
08-19 11:01:10.420: INFO/(1371): Alarm Running for 0
08-19 11:01:12.419: INFO/(1371): Alarm Running for 0
08-19 11:01:14.419: INFO/(1371): Alarm Running for 0
08-19 11:01:16.420: INFO/(1371): Alarm Running for 0
08-19 11:01:18.420: INFO/(1371): Alarm Running for 0

现在这对我来说意味着意图不包含我给它的“开始”额外内容putExtra()

如何通过意图附加或其他方法判断警报的寿命?

编辑:我可以通过创建一个静态 int 并在每次警报代码执行时递增它来找出接收类已接收广播的次数,但这不是查找“年龄”的好方法”。

更新:结合Mobius提供的答案,您还必须在PendingIntent.getBroadcast()中传递PendingIntent.FLAG_UPDATE_CURRENT,如下所示:

PendingIntent sender = PendingIntent.getBroadcast(Main.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

I have a setRepeating() alarm scheduled that I want to disable in it's BroadcastReceiver if it is of a certain age. I would rather disable it inside of the BroadcastReceiver, so if its possible that would be my first choice.

In my Activity:

// Start our alarm
Intent intent = new Intent(Main.this, Receiver.class);

long firstTime = SystemClock.elapsedRealtime();
firstTime += 2 * 1000; // start in 2 seconds
long interval = 2000; // 2 seconds for testing

intent.putExtra("start", firstTime); // Tell the receiver the creation date (not working)

PendingIntent sender = PendingIntent.getBroadcast(Main.this, 0, intent, 0);

// Schedule the alarm!
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, interval, sender);

In my BroadcastReceiver:

@Override
public void onReceive(Context context, Intent intent) {
    // ... alarm stuff
    long now = SystemClock.elapsedRealtime();
    Log.i("", "Alarm Running for " + (now - intent.getLongExtra("start", now)));
    //getLongExtra() defaults to 'now' because there is no extra 'start'
}

In LogCat I see this..

08-19 11:01:04.420: INFO/(1371): Alarm Running for 0
08-19 11:01:06.420: INFO/(1371): Alarm Running for 0
08-19 11:01:08.430: INFO/(1371): Alarm Running for 0
08-19 11:01:10.420: INFO/(1371): Alarm Running for 0
08-19 11:01:12.419: INFO/(1371): Alarm Running for 0
08-19 11:01:14.419: INFO/(1371): Alarm Running for 0
08-19 11:01:16.420: INFO/(1371): Alarm Running for 0
08-19 11:01:18.420: INFO/(1371): Alarm Running for 0

Now this to me means that the intent does not contain the "start" extra that I gave it with putExtra().

How do I tell the age of an alarm, either by intent extras or other methods?

Edit: I can find out how many times the Receiving class has received the broadcast by creating a static int and incrementing it every time the alarm code executes, but this is not a good way to find the "age".

Update: In combination from the answer provided by Mobius, you must also pass PendingIntent.FLAG_UPDATE_CURRENT in PendingIntent.getBroadcast(), like follows:

PendingIntent sender = PendingIntent.getBroadcast(Main.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

帅哥哥的热头脑 2024-12-07 05:57:10

您尝试过使用捆绑包吗?

在 onReceive() 内部

Bundle myBundle = intent.getExtras();
    if (myBundle != null) {
        long startTime = myBundle.get("start");
}

Have you tried using a Bundle?

inside onReceive()

Bundle myBundle = intent.getExtras();
    if (myBundle != null) {
        long startTime = myBundle.get("start");
}
只怪假的太真实 2024-12-07 05:57:10

我不确定 onReceive() 方法中的第二个参数是否是来自 Activity 的意图。是 AlarmManager 正在启动接收器,而不是您的活动。如果我是对的,我的脑海中只有一种解决方案可以解决您的问题 - 外部存储的文件,其中包含闹钟的开始时间。

它是这样的:

  1. 活动

    // 记住添加
    // <使用权限 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    // 在你的清单 xml 中
    文件 file = new File(Environment.getExternalStorageDirectory() + "/yourAppsName",
            “.alarmStartTime”);
    尝试 {
        BufferedWriter out = new BufferedWriter(new FileWriter(file.getAbsolutePath(), true));
        out.write(SystemClock.elapsedRealtime());
        关闭();
    } catch (IOException e) {
        Toast.makeText(this.getApplicationContext(), "问题", Toast.LENGTH_SHORT).show();
    }
    
  2. BroadcastReceiver

    文件 file = new File(Environment.getExternalStorageDirectory() + "/yourAppsName",
            “闹钟开始时间.txt”);
    字符串内容=“”;
    尝试 {
        内容 = new Scanner(file).useDelimiter("\\Z").next();
    } catch (FileNotFoundException e) {
        Toast.makeText(this.getApplicationContext(), "问题", Toast.LENGTH_SHORT).show();
    }
    Log.i("", "闹钟运行时间为 " + (SystemClock.elapsedRealtime() - Long.decode(content)));
    

不过,如果你每 2 秒运行一次,它就会成为 cpu 和电池杀手;)

再告诉我一次,为什么你不能使用这个静态变量?如果您在警报之间有特定的间隔,则迭代次数可以简单地告诉您接收器的使用寿命。

I'm not sure if the second argument in the onReceive() method is the intent from Activity. Its the AlarmManager who's firing up the receiver, not your activity. If i'm right, my mind has only one solution for your problem - file stored externally, containing your alarm's start time.

It goes like this:

  1. Activity:

    // Remember about adding
    // <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    // in your manifest xml
    File file = new File(Environment.getExternalStorageDirectory() + "/yourAppsName",
            ".alarmStartTime");
    try {
        BufferedWriter out = new BufferedWriter(new FileWriter(file.getAbsolutePath(), true));
        out.write(SystemClock.elapsedRealtime());
        out.close();
    } catch (IOException e) {
        Toast.makeText(this.getApplicationContext(), "Problem", Toast.LENGTH_SHORT).show();
    }
    
  2. BroadcastReceiver:

    File file = new File(Environment.getExternalStorageDirectory() + "/yourAppsName",
            "alarmStartTime.txt");
    String content = "";
    try {
        content = new Scanner(file).useDelimiter("\\Z").next();
    } catch (FileNotFoundException e) {
        Toast.makeText(this.getApplicationContext(), "Problem", Toast.LENGTH_SHORT).show();
    }
    Log.i("", "Alarm Running for " + (SystemClock.elapsedRealtime() - Long.decode(content)));
    

Although, its a cpu and battery killer if you'd run it every 2 seconds;)

Tell me again why can't you use this static variable? If you have specific interval between alarms, number of iterations can simply inform you about life span of the receiver.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文