Biswajit
Biswajit

Reputation: 339

Implementation of periodic task in android

I want to create a small android app that would show the system time in periodic intervals after clicking on a button ( i.e. setting the activity up )...The code for button creation and setting the periodic activity via Intent goes like this :

package com.example.timeupdate;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

Button button;
TextView show;

@Override
protected void onCreate(Bundle I_Love_Biriyani) {
    super.onCreate(I_Love_Biriyani);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById (R.id.pressButton);
    show = (TextView) findViewById (R.id.Show);

    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            Intent openTimeUpdater = new Intent("com.example.timeupdate.TIMEUPDATER");
            startActivity(openTimeUpdater);

        }
    });

}


@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    finish();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}



}

And here is the code for repeating the timer( for say 5 seconds ) where I used TimerTask class to perform the job :

package com.example.timeupdate;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class TimeUpdater extends Activity {

    TextView Show;

    TimerTask timer= new TimerTask(){

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Date d = new Date();
            Show.setText(""+d);
        }

    };

    @Override
    protected void onCreate(Bundle hotovaga) throws IllegalStateException {
        // TODO Auto-generated method stub
        super.onCreate(hotovaga);
        setContentView(R.layout.new_update);

        Show = (TextView) findViewById (R.id.time);

        Timer t = new Timer();
        t.scheduleAtFixedRate(timer , 0 , 5000);

    }


}

After clicking on the button the time is shown only once then application is getting stopped showing a dialog-message. Need explanations to do this job in the same fashion.

Upvotes: 0

Views: 3837

Answers (3)

TeeTracker
TeeTracker

Reputation: 7350

use PeriodicTask from Play-Service, it is the newest tool from Google to schedule a job background.

Upvotes: 0

Jitesh Dalsaniya
Jitesh Dalsaniya

Reputation: 1917

Using an actual Timer (java.util.Timer) in conjunction with runOnUiThread() is one way to solve this issue, and below is an example of how to implement it.

public class myActivity extends Activity {

private Timer myTimer;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    myTimer = new Timer();
    myTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            TimerMethod();
        }

    }, 0, 1000);
}

private void TimerMethod()
{
    //This method is called directly by the timer
    //and runs in the same thread as the timer.

    //We call the method that will work with the UI
    //through the runOnUiThread method.
    this.runOnUiThread(Timer_Tick);
}

private Runnable Timer_Tick = new Runnable() {
    public void run() {

    //This method runs in the same thread as the UI. 
    // Set your textView data here.              

    //Do something to the UI thread here

    }
};
}

Upvotes: 0

Abhishek V
Abhishek V

Reputation: 12526

You are trying to access an UI element inside non-UI thread.

Show.setText(""+d);

Instead, wrap it up in runOnUiThread interface to get proper output.

Use below code for your TimeUpdater class

public class TimeUpdater extends Activity {


    TextView Show = null;
    Calendar c; 
    int seconds;
    int minutes;
    int hours;

    TimerTask timer= new TimerTask(){

        @Override
        public void run() {
            c = Calendar.getInstance();
            seconds = c.get(Calendar.SECOND);
            minutes = c.get(Calendar.MINUTE);
            hours = c.get(Calendar.HOUR);

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Show.setText(hours + ":" + minutes + ":" + seconds);
                }
            });
        }

    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_update);

        Show = (TextView) findViewById (R.id.time);

        Timer t = new Timer();
        t.scheduleAtFixedRate(timer , 0 , 5000);


    }

}

Upvotes: 1

Related Questions