1
我正在嘗試使用AlarmManager
找到我的BroadcastReceiver
的PendingIntent
。PendingIntent.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嗎?
我正在這樣做,看看我的鬧鐘是否已安排。您能否解釋'返回與給定參數匹配的現有或新的PendingIntent。只有在提供了FLAG_NO_CREATE的情況下才可以返回null。'從getBroadcast()的[Android參考](http://developer.android.com/reference/android/app/PendingIntent.html)?我認爲它會返回null,如果它不存在。 – styler1972
@Styler:「我正在這樣做,看看我的鬧鐘是否已安排。」 - 在您自己的持久性存儲區中記下這一點,例如文件或數據庫。 「我認爲如果它不存在就會返回null」 - 我同意,儘管在源代碼中,我沒有看到它實際上存在這種行爲。 :-(通過文件或數據庫自己跟蹤你的警報將更加可靠恕我直言。 – CommonsWare