【问题标题】:How to use requestCode in PendingIntents如何在 PendingIntents 中使用 requestCode
【发布时间】:2013-03-31 15:52:17
【问题描述】:

我正在尝试实现一个提醒应用程序。我将所有提醒详细信息存储在 sqlite 数据库中,例如 id、title、dateInfo、timeInfo 等。

我想在适当的时候通知用户我将使用 AlarmManager 的提醒。

下面给出的步骤是否可行。

在pendentingIntents 中提供行的id 作为requestCode。 然后设置一个警报,一旦触发就会调用服务。 该服务将使用此 ID 从数据库中获取数据。

如果这是可行的,任何人都可以提供一个代码sn-p。

任何帮助将不胜感激

【问题讨论】:

    标签: android android-service alarmmanager android-pendingintent


    【解决方案1】:

    您可以简单地将您的 rowId 作为额外内容放入被调用的意图中。这是一个可能有帮助的代码 sn-p:

    Intent i = new Intent(this, YourServiceOrActivity.class);
    i.putExtra("rowId", rowId);
    PendingIntent pi = PendingIntent.getActivity(this, 123123, i, 0); //Notice the random requestCode '123123' as it doesn't matter, yet.
    

    您可以按如下方式设置闹钟:

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, AlarmManager.INTERVAL_DAY, pi); 
    //Set the alarm to wake up the device after one day calling the pending intent 'pi'.
    

    最后你可以从intent中获取rowId(onCreate(),例如intent是一个Activity),调用如下:

    Bundle extras = getIntent().getExtras();
    if (extras != null) rowId = extras.getInt("rowId", 0); //Be safe
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      正如其他人提到的那样,我会将rowId 作为额外的,但是不要误会 - 正如PendingIntent 文档中所写,意图如下:

      如果您确实需要同时激活多个不同的 PendingIntent 对象(例如用作同时显示的两个通知),那么您将需要确保它们之间存在一些不同的东西可以关联它们具有不同的 PendingIntents。这可能是 Intent 考虑的任何 Intent 属性。 filterEquals 或 不同的请求代码 提供给 getActivity(Context, int, Intent, int)、getActivities(Context, int, Intent[], int), getBroadcast(Context, int, Intent, int) 的整数, 或 getService(Context, int, Intent, int)。

      因此,如果您为同一行的所有意图使用相同的 id 请求,使用不同的数据,您可能会因过时/重复数据问题而迷失方向。

      【讨论】:

        【解决方案3】:

        根据PendingIntent 上的文档,不使用getService(...) 方法的requestCode。我不清楚它会发生什么,所以我不会以任何方式依赖它。

        只需将行 ID 作为额外的 Intent 传递。

        【讨论】:

        • 我可以将 rowId 传递给 alaramManager,然后将其转发给服务吗? @karakuri
        • 编辑了我的帖子。使用额外的意图,它将避免混淆,并且如果系统以某种方式在内部使用该值,则不会发生任何奇怪的行为。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        相关资源
        最近更新 更多