如何使用按钮终止从IntentService创建的TimerTask

时间:2012-06-18 23:34:25

标签: android cloud intentservice

我正在制作一个使用标准HTTP获取命令的Cloud Service。我使用服务(扩展类IntentService而不是Service)来保持同步。我在TimerTask中每隔3秒开始检查一次。问题是,当用户返回活动以便在需要时将其关闭时,他们会按下切换按钮。如何告诉TimerTask(或运行计时器任务的IntentService)停止并启动它?

服务本身在处理意图并创建任务后会被破坏,因此服务比IntentService更适合这个吗?即使这样,关于停止和启动TimerTask的问题仍然存在。

这是intentservice的代码:

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.widget.*;

public class syncservice extends IntentService {

  /** 
   * A constructor is required, and must call the super IntentService(String)
   * constructor with a name for the worker thread.
   */
    public syncservice() {
        super("syncservice");
    }
    public static final String PREFS_NAME = "prefcs";
  /**
   * The IntentService calls this method from the default worker thread with
   * the intent that started the service. When this method returns, IntentService
   * stops the service, as appropriate.
   */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    final String uid = intent.getExtras().get("uid").toString();
    final String dvname = intent.getExtras().get("dvname").toString();
    final long period = intent.getExtras().getLong("period");
    final Context ctx = getApplicationContext();
    final Toast toast = Toast.makeText(ctx,"An error occured with the service. It will automatically turn off.", 0);
    final Handler handler = new Handler();
    TimerTask timertask = new TimerTask () {
        @Override
        public void run() {
            SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
            if (settings.getBoolean("doservice", false)) {
                String command = netread("url here");
                //TODO Parse command from Pulling
                if (command.contains("<")) {
                    //TODO what to do if an error occurred (exceptions already caught
                    Runnable showerrormessage = new Runnable() {
                        public void run() {
                            toast.makeText(ctx,"new text",0);
                            toast.show();
                        }
                    };
                    handler.post(showerrormessage);
                }
            }
        }
    };
    Timer timer = new Timer();
    timer.schedule(timertask,0,period);
    return super.onStartCommand(intent,flags,startId);
}
public void onDestroy() {
    Toast.makeText(getApplicationContext(), "The Service has died", Toast.LENGTH_SHORT).show();
    return;
}

@Override
protected void onHandleIntent(Intent intent) {
    Toast.makeText(getApplicationContext(), "Intent Handled", 0).show();
}
public final String netread(String url) {
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        ResponseHandler<String> resHandler = new BasicResponseHandler();
        String page = httpClient.execute(httpGet, resHandler);
        return page;
    } catch (ClientProtocolException e) {
        //Toast.makeText(getApplicationContext(),"Client Protocol Exception! Try again.",0).show();
        return "<";
    } catch (IOException e) {
        //Toast.makeText(getApplicationContext(),"IO Exception! Make sure you are connected to the internet and try again.", 0).show();
        return "<";
    }

}
}

非常感谢帮助我!

1 个答案:

答案 0 :(得分:0)

对于您要做的事情,Handler可能更有用。该链接BTW还显示了如何从UI中停止它。