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

Android 如何使用按钮终止从IntentService创建的TimerTask,android,cloud,intentservice,Android,Cloud,Intentservice,我正在制作一个云服务,它使用标准的HTTPGET命令。我使用服务(扩展类IntentService而不是服务)来保持同步。我会在一个计时器中检查每3秒启动一次。问题是,当用户返回活动以关闭它时,如果他们愿意,他们会按一个切换按钮。如何告诉TimerTask(或运行计时器任务的IntentService)停止并启动它 在处理intent并创建任务之后,服务本身将被销毁,因此服务是否比IntentService更适合于此?即使是这样,关于停止和启动TimerTask的问题仍然存在 以下是intent

我正在制作一个云服务,它使用标准的HTTPGET命令。我使用服务(扩展类IntentService而不是服务)来保持同步。我会在一个计时器中检查每3秒启动一次。问题是,当用户返回活动以关闭它时,如果他们愿意,他们会按一个切换按钮。如何告诉TimerTask(或运行计时器任务的IntentService)停止并启动它

在处理intent并创建任务之后,服务本身将被销毁,因此服务是否比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 "<";
    }

}
}
import java.io.IOException;
导入java.util.Timer;
导入java.util.TimerTask;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.ResponseHandler;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.impl.client.BasicResponseHandler;
导入org.apache.http.impl.client.DefaultHttpClient;
导入android.app.*;
导入android.content.Context;
导入android.content.Intent;
导入android.content.SharedReferences;
导入android.os.Handler;
导入android.widget.*;
公共类syncservice扩展了IntentService{
/** 
*构造函数是必需的,并且必须调用超级IntentService(字符串)
*具有工作线程名称的构造函数。
*/
公共服务(){
超级(“同步服务”);
}
公共静态最终字符串PREFS_NAME=“prefcs”;
/**
*IntentService使用默认工作线程调用此方法
*启动服务的意图。此方法返回时,IntentService
*根据需要停止服务。
*/
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
最后一个字符串uid=intent.getExtras().get(“uid”).toString();
最后一个字符串dvname=intent.getExtras().get(“dvname”).toString();
最终长周期=intent.getExtras().getLong(“周期”);
最终上下文ctx=getApplicationContext();
final Toast Toast=Toast.makeText(ctx,“服务出现错误。它将自动关闭。”,0);
最终处理程序=新处理程序();
TimerTask TimerTask=新的TimerTask(){
@凌驾
公开募捐{
SharedReferences设置=GetSharedReferences(首选项名称,0);
if(settings.getBoolean(“doservice”,false)){
String命令=netread(“此处的url”);
//TODO解析来自拉取的命令

if(command.contains)(“对于您尝试执行的操作,可能更有用。该链接BTW还显示了如何从UI停止该操作。

对于您尝试执行的操作,可能更有用。该链接BTW还显示了如何从UI停止该操作