0

嗨,我正在尝试创建一个简单的程序来安排在单击按钮时的一段时间后触发的事件。

对于我下面的代码,我可以一次将所有收到的事件放在一起,而不是按表格间隔。

代码如下:

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 
4

2 回答 2

0

一些东西:

- 不要每次点击都注册一个接收者。做一次(例如在你的 onCreate 中)。

- 为了让您在同一个广播中获得不同的 onReceive 调用,您需要为每个待处理的意图添加一个请求代码。您可以为此使用“计数”。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    am = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));

    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"));

    findViewById(R.id.the_button).setOnClickListener(this);
}

@Override
public void onClick(View v) {
    pi = PendingIntent.getBroadcast(this, count, new Intent(
            "com.text.timer"), 0);
    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();
}
于 2013-06-29T06:11:47.877 回答
0

是一个很好的结论……不过,不确定这个问题。但是,我发现该链接很有用。

于 2013-06-29T05:49:56.533 回答