遇到如下问题
pendingintent传值经常获取到的值是第一次的值或者null,这个跟第二个参数和最后一个参数选择有关系.
将最后一个参数设置成
PendingIntent.FLAG_UPDATE_CURRENT
即可解决问题。
代码
注意:此代码仅仅实现延时操作,若需要循环发送,需要在receiver将service启动。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
int random;
// get a random number
random = (int)(Math.random() * 10 + 1);
long triggerTime = SystemClock.elapsedRealtime() + 5 * 1000;
// get pid and tid
int pid = Process.myPid();
long tid = Process.myTid();
Intent i = new Intent(SEND_ACTION);
i.putExtra(RANDOM_NUM, random);
i.putExtra(SERVICE_PID, pid);
i.putExtra(SERVICE_TID, tid);
// get a pending intent which can send braodcast
PendingIntent pi = PendingIntent
.getBroadcast(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
// 5seconds later send the pendingintent
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerTime, pi);
return super.onStartCommand(intent, flags, startId);
}