开发者

How to control an Android service?

开发者 https://www.devze.com 2023-02-15 09:45 出处:网络
I\'m currently developing my first android application. I want the user of my application to be able to activate \"automatic update of data\" which means that some data should be refreshed every x min

I'm currently developing my first android application. I want the user of my application to be able to activate "automatic update of data" which means that some data should be refreshed every x minutes. I've created a service which is started by

service = new Intent(context, MyService.class);
context.startService(service);

and I'm using a TimerTask within the service to periodically refresh the data.

timer = new Timer();

TimerT开发者_JAVA百科ask tt = new TimerTask() {
    public void run() {
        refreshData();
    }
};
timer.scheduleAtFixedRate(tt,0,interval);

I've noticed that the service can be restarted now and then. How can I ensure that refreshData(); is run every interval minute (not more or less)? If the user changes the interval (preference) how do a kill the current timer(task) and start a new one? Right now it seems to start a new one but not killing the old making refreshData() to execute according to two intervals.

Any help is appreciated!


(I'm new to android developing also so take everything i say with a grain of salt)

Well it looks to me like you have a lot of thinking to do about structure. There are different ways to communicate with the service. I think that the best option would be to broadcast an intent, make the service receive the intent and change the interval based on the information received from the intent.

0

精彩评论

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