shumengma
shumengma

Reputation: 33

Timer.schedule different in Activity and BroadcastReceiver

I schedule a timeatsk twice in activity(click the button twice),like this:

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.btn_timer:
            addTimer();
            break;
    }
}
private void addTimer(){
    Log.e("----","------"+Thread.currentThread().getName());
    if(timerTask == null){
        timerTask = new TimerTask() {
            @Override
            public void run() {
                timerCount++;
                Log.e("----","------=="+Thread.currentThread().getName());
                Log.e("------","------"+timerCount);
            }
        };
    }
    if(timer == null){
        timer = new Timer();
        timer.schedule(timerTask,1000,1000);
    }
}

result is :

the right result

but I schedue the same task in BroadcastReceiver twice(click the button twice): inActivity:

 @Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.btn_timer:
            Intent intent = new Intent();
            intent.setAction("timer");
            this.sendBroadcast(intent);
            break;
    }
}

in broadcastReceiver:` @Override public void onReceive(Context context, Intent intent) { addTimer(); }

private void addTimer(){
    Log.e("----",Thread.currentThread().getName());
    if(timerTask == null){
        timerTask = new TimerTask() {
            @Override
            public void run() {
                timerCount++;
                Log.e("----","------=="+Thread.currentThread().getName());
                Log.e("------","------"+timerCount);
            }
        };
    }
    if(timer == null){
        timer = new Timer();
        timer.schedule(timerTask,1000,1000);
    }
}`

but the result is in two thread!

Upvotes: 0

Views: 277

Answers (1)

gjsalot
gjsalot

Reputation: 768

What is happening is that you only have one instance of your Activity and so the second time you call addTimer(), timerTask and timer are non-null (because you already assigned them on the first click). Thus you only have a single timer.

Each time you send a broadcast a new broadcast receiver instance is created. Each instance will create it's own timerTask and timer (because they are null). Thus you will end up with multiple timers.

What are you actually trying to achieve with these timers?

Upvotes: 0

Related Questions