嗨,我正在尝试创建一个简单的程序来安排在单击按钮时的一段时间后触发的事件。
对于我下面的代码,我可以一次将所有收到的事件放在一起,而不是按表格间隔。
代码如下:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.the_button).setOnClickListener(this);
}
private void setup() {
br = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
Date d = new Date();
CharSequence s = DateFormat.format("mm:ss ", d.getTime());
Log.i("trigger"," " + s);
}
};
registerReceiver(br, new IntentFilter("com.text.timer") );
pi = PendingIntent.getBroadcast( this, 0, new Intent("com.text.timer"), 0 );
am = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
}
@Override
public void onClick(View v) {
setup();
am.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + TWENTY_SECONDS, pi );
Date d = new Date();
CharSequence s = DateFormat.format("mm:ss ", d.getTime());
Log.i("clicked"," " + s);
count++;
}
@Override
protected void onDestroy() {
am.cancel(pi);
unregisterReceiver(br);
super.onDestroy();
}
我的 Logcat 测试结果
06-29 05:04:05.501: I/clicked(1849): 04:05
06-29 05:04:06.561: I/clicked(1849): 04:06
06-29 05:04:07.551: I/clicked(1849): 04:07
06-29 05:04:09.621: I/trigger(1849): 04:09
06-29 05:04:09.651: I/trigger(1849): 04:09
06-29 05:04:09.701: I/trigger(1849): 04:09
06-29 05:04:09.741: I/trigger(1849): 04:09
06-29 05:04:09.781: I/trigger(1849): 04:09