PendingIntent.getBroadcast()永远不会返回null

时间:2011-09-01 16:22:37

标签: android broadcastreceiver

我正在尝试查找使用PendingIntent调用的BroadcastReceiver AlarmManager

我正在使用PendingIntent.getBroadcast()使用与调用它相同的参数,但它永远不会返回null。

public MyObject(Context context, AnotherObject object) {

    Intent i;
    i = new Intent(context, MyReceiver.class);
    i.putExtra(AnotherObject.SOMETHING, "string");
    i.putExtra(AnotherObject.SOME_BOOL, true);

    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_NO_CREATE);

    if (pi == null) {
        Log.v("help", "PendingIntent is null");
    }
    else {
        Log.v("help", "PendingIntent is not null");
    }
}

这是我的测试驱动程序:

that = new MyObject(this, object);

LogUtil.startAlarm(this, object);

that = new LogUtil(this, object);

这是startAlarm

public static void startAlarm(Context that, AnotherObject object) {

    Intent i;
    i = new Intent(that, MyReceiver.class);
    i.putExtra(AnotherObject.SOMETHING, "string");
    i.putExtra(AnotherObject.SOME_BOOL, true);

    long interval = 60 * 1000; // Minute
    long first = SystemClock.elapsedRealtime() + interval;

    PendingIntent pi = PendingIntent.getBroadcast(that, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

    // Schedule the alarm
    AlarmManager am2 = (AlarmManager) that.getSystemService(Context.ALARM_SERVICE);
    am2.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, first, interval, pi);
    Log.v("help", "Started alarm");
}

这是我的日志输出:

09-02 11:18:54.330: VERBOSE/help(9621): PendingIntent is not null
09-02 11:18:54.330: VERBOSE/help(9621): Started alarm
09-02 11:18:54.330: VERBOSE/help(9621): PendingIntent is not null

为什么它甚至在我开始闹钟之前就说它永远不会为空? getBroadcast()不应该返回null吗?

1 个答案:

答案 0 :(得分:3)

  

我试图找到使用AlarmManager调用的BroadcastReceiver的PendingIntent。

嗯,为什么?

  

我正在使用PendingIntent.getBroadcast()使用与它一起调用的相同参数,但它永远不会返回null。

不应该这样。如果还没有一个用于等效的基础PendingIntent,它将创建Intent。有人可能会争辩说方法名称应该是createBroadcast()以使这一点更清晰。