2011-09-01 91 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