2012-06-18 1 views
2

표준 HTTP get 명령을 사용하는 클라우드 서비스를 만들고 있습니다. 나는 (서비스와 반대로 IntentService 클래스를 확장하는) 서비스를 사용하여 상황을 동기화시킨다. 나는 매 3 초마다 발사되는 TimerTask에서 계속 점검을하고있다. 문제는 사용자가 원하는 경우 활동을 종료 할 때 토글 버튼을 누르는 것입니다. TimerTask (또는 Timer 태스크를 실행중인 IntentService)에게이를 중지하고 시작하도록 알리는 방법은 무엇입니까?단추로 IntentService에서 생성 된 TimerTask를 삭제하는 방법

서비스 자체가 의도를 처리하고 작업을 생성 한 후에 서비스 자체가 파괴되므로 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 "<"; 
    } 

} 
} 

감사합니다 저를 도와 주셔서 무리!

답변

0

당신이하려는 일에 대해서는 Handler이 더 유용 할 수 있습니다. BTW 링크는 UI에서이를 중지하는 방법을 보여줍니다.