从活动中发送额外内容以广播接收者

时间:2018-12-21 13:53:29

标签: android android-broadcastreceiver

我的应用程序是关于提醒的。将提醒插入SQLite数据库后,它在AddReminderActivity.java类中正确显示了ID,但在以下代码中在AlarmReciver.java类中返回了ID = 1。

这就是我要投入的东西

       Intent intent = new Intent(this, AlarmReciever.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    intent.putExtra("reminderId", reminderId);
    PendingIntent pendingIntent = 
    PendingIntent.getBroadcast(this.getApplicationContext(), 5, intent, 0);

    AlarmManager mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    assert mAlarmManager != null;
    mAlarmManager.set(AlarmManager.RTC_WAKEUP, milliSecondsFromDate, pendingIntent);

    Toast.makeText(this, "Alarm set at " + selectedDate + " " + timeInHrs, Toast.LENGTH_LONG).show();
    finish();

这就是我获得额外奖励的方式

@Override
public void onReceive(Context context, Intent intent) {

    Long reminderId = intent.getLongExtra("reminderId", -1);
    mDatabaseHelper = new DatabaseHelper(context);
    Reminder reminder = mDatabaseHelper.getReminder(reminderId);

    Intent serviceIntent = new Intent(context, TTSService.class);
    if (reminder != null && !reminder.getText().isEmpty()) {
        serviceIntent.putExtra("reminderText", reminder.getText());
    }
    context.startService(serviceIntent);

    Toast.makeText(context, "AlarmReciever..", Toast.LENGTH_LONG).show();

}

2 个答案:

答案 0 :(得分:0)

使用它来获得更多

@Override
public void onReceive(Context context, Intent intent) {

    Long reminderId = intent.getExtras().getLong("reminderId", -1);
    mDatabaseHelper = new DatabaseHelper(context);
    Reminder reminder = mDatabaseHelper.getReminder(reminderId);

    Intent serviceIntent = new Intent(context, TTSService.class);
    if (reminder != null && !reminder.getText().isEmpty()) {
        serviceIntent.putExtra("reminderText", reminder.getText());
    }
    context.startService(serviceIntent);

    Toast.makeText(context, "AlarmReciever..", Toast.LENGTH_LONG).show();

}

答案 1 :(得分:0)

为了正确设置“附加”,您需要在对PendingIntent.FLAG_UPDATE_CURRENT的调用中使用getBroadcast(),如下所示:

PendingIntent pendingIntent = 
    PendingIntent.getBroadcast(this.getApplicationContext(), 5, intent,
        PendingIntent.FLAG_UPDATE_CURRENT);

还确定在调用reminderId的代码中long的类型为LongputExtra()吗?