开发者

Cannot read currentTimeMillis in BroadcastReceiver

I'm trying to measure how long each Bluetooth discovery process takes place. I assign currentTimeMillis to startTime and stopTime. When I put the BroadcastReceiver class as inner class, I can read both variables, but when I make it as an outer 开发者_StackOverflowclass, I cannot read startTime. Here is my code,

private long startTime;
private long stopTime;

@Override
public void onReceive(Context context, Intent intent) {
    String strIntent = intent.getAction();
    if (strIntent.equalsIgnoreCase(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
        handleDiscStarted();
    } else if (strIntent.equalsIgnoreCase(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
        handleDiscFinished();
    }
}

private void handleDiscStarted() {
    startTime = System.currentTimeMillis();
    Log.d(tag, "\nDiscovery started " + startTime);
}

private void handleDiscFinished() {
    stopTime = System.currentTimeMillis();
    Log.d(tag, "\nDiscovery finished " + stopTime + ", takes " + (stopTime-startTime) + " ms");
    // startTime = 0 here...
    Log.d(tag, "\nstopTime=" + stopTime + ", startTime=" + startTime);
}

Any idea why the different behaviors occur? How can I read startTime in the second case? Thanks!


Taken from the Receiver Lifecycle:

A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent).

Therefore the start time you initially recorded will not exist when you calculate the end time.

If you want to keep track of this start time appropriately, I suggest keeping track of it in persistent storage, in this case SharedPreferences.


Try it like this. Start the counting from the onClick() send the initial time in the intent data to the BroadcastReciever, and when you finish the discovery just substract with the final time you get in the BroadcastReciever. It's just another way around to avoid loosing of start time. If you are calling start and stop of discovery from the same button make sure the logic works, and do not send the initial time twice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜