Sourav301
Sourav301

Reputation: 1259

Respond to change in variable

I have made a service that displays a toast showing the current time . The toast should be displayed when the value of "minute" changes. What should i do ? Here is the code. Is it necessary to create a listener to listen to change of the minute variable? Please help me.

public class Servicedemo extends Service{
@Override
public void onCreate() {

    super.onCreate();
    Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
     String str;

        Calendar c=Calendar.getInstance();
        int hour=c.get(Calendar.HOUR);
        int min=c.get(Calendar.MINUTE);
        str=String.valueOf(hour)+":"+String.valueOf(min);

        Toast.makeText(this, str , Toast.LENGTH_SHORT).show();

}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}


}

Upvotes: 1

Views: 91

Answers (1)

koleanu
koleanu

Reputation: 495

you need create one timertask and override run method, like :

    public class yourAsyncTimerTask extends TimerTask{

    @Override
    public void run() {
                Calendar c=Calendar.getInstance();
                int hour=c.get(Calendar.HOUR);
                int min=c.get(Calendar.MINUTE);
                String str = String.valueOf(hour)+":"+String.valueOf(min);

            Toast.makeText(this, str , Toast.LENGTH_SHORT).show();

    }

}

and set your timer

Timer timer = new Timer();      
timer.schedule(new yourAsyncTimerTask(), 1 * 60 * 1000,  1 * 60 * 1000);

Upvotes: 2

Related Questions