【问题标题】:My receiver don't receive the intent我的接收者没有收到意图
【发布时间】:2016-04-29 16:14:37
【问题描述】:

我有这个问题:我将alarmManager设置为intent和pendingintent,如果满足某些条件,在intent中添加一些额外的东西。 问题是我的接收器没有读取我的附加内容:

在MainActivity中设置alarmManager:

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(MainActivity.this, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this , 0, i, PendingIntent.FLAG_ONE_SHOT);

       // conditions 
                    i.putExtra("type", 1);
                    i.putExtra("mealType", 2);
                    Log.d(TAG , "type: " + i.getExtras().getInt("type"));
                    Log.d(TAG , "mealtype: " + i.getExtras().getInt("mealType"));
                    calendar.set(calendar.HOUR_OF_DAY, 7);
                    am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);

在 logcat 中我可以看到:

D/MAIN: type: 1
D/MAIN: mealtype: 2

但在我的接收器中:

public void onReceive(Context context, Intent intent) {

    /**
     * Receiver
     */
    Log.d(TAG, "Allarme ricevuto dal receiver");

    int type = intent.getExtras().getInt("type");
    Log.d(TAG , "type: " + type);
    Log.d(TAG , "mealtype: " + intent.getExtras().getInt("mealType"));
    Log.d(TAG , "unExisted: " + intent.getExtras().getInt("unExisted"));



    if(type == 0){
        Intent service = new Intent(context, AlarmService.class);
        service.putExtra("type", type);
        context.startService(service);
    }

    if(type == 1){
        int mealType = intent.getExtras().getInt("mealType");

        Intent service1 = new Intent(context, AlarmService.class);
        service1.putExtra("type", type);
        service1.putExtra("mealType", mealType);
        context.startService(service1);
    }
}

我看到了:

D/ALARM RECEIVER: Allarme ricevuto dal receiver
D/ALARM RECEIVER: type: 0
D/ALARM RECEIVER: mealtype: 0
D/ALARM RECEIVER: unExisted: 0

我将 all'key 视为 0,也将其视为 0“unExistest”,我从未在意图中插入此密钥。为什么?

【问题讨论】:

    标签: android android-intent broadcastreceiver android-pendingintent extras


    【解决方案1】:

    您需要在创建PendingIntent 之前设置Intent extras。

    例子:

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(MainActivity.this, AlarmReceiver.class);
    i.putExtra("type", 1);
    i.putExtra("mealType", 2);
    PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this , 0, i, PendingIntent.FLAG_ONE_SHOT);
    calendar.set(calendar.HOUR_OF_DAY, 7);
    am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);
    

    【讨论】:

    • 非常感谢,没想到这么简单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    相关资源
    最近更新 更多