2011-09-01 97 views
1

我正在尝试使用AlarmManager找到我的BroadcastReceiverPendingIntentPendingIntent.getBroadcast()永不返回空

我使用的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 

它为什么说这是从来没有null,甚至在我开始之前电子闹钟? getBroadcast()不应该返回null吗?

回答

3

我想找到使用AlarmManager调用的BroadcastReceiver的PendingIntent。

嗯,为什么?

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

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

+0

我正在这样做,看看我的闹钟是否已安排。您能否解释'返回与给定参数匹配的现有或新的PendingIntent。只有在提供了FLAG_NO_CREATE的情况下才可以返回null。'从getBroadcast()的[Android参考](http://developer.android.com/reference/android/app/PendingIntent.html)?我认为它会返回null,如果它不存在。 – styler1972

+0

@Styler:“我正在这样做,看看我的闹钟是否已安排。” - 在您自己的持久性存储区中记下这一点,例如文件或数据库。 “我认为如果它不存在就会返回null” - 我同意,尽管在源代码中,我没有看到它实际上存在这种行为。 :-(通过文件或数据库自己跟踪你的警报将更加可靠恕我直言。 – CommonsWare