2015-01-01 56 views
1

即時跟隨教程鏈接http://www.coderzheaven.com/2012/07/14/ http請求-call-repeated-service-android但有點混淆下面的代碼,使http調用重複,所以onstart()方法或onstartcommand()被重複調用,一旦它的開始線程mythread.start();已完成或由於在onstart()方法中檢查了flag,所以,onstart()方法會在線程啓動完成後重複,或者線程啓動完成後返回onstart()。請讓我清楚。提前感謝。onstartcommand服務類的方法被重複調用,當startservice一旦從活動類觸發

以下是代碼 - >>

package com.coderzheaven.pack; 

import org.apache.http.client.HttpClient; 
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.Service; 
import android.content.Intent; 
import android.os.IBinder; 
import android.util.Log; 

public class MyService extends Service{ 

    private static String TAG = MyService.class.getSimpleName(); 
    private MyThread mythread; 
    public boolean isRunning = false; 

    @Override 
    public IBinder onBind(Intent arg0) { 
     <span id="IL_AD9" class="IL_AD">return</span> null; 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     Log.d(TAG, "onCreate");  
     mythread = new MyThread(); 
    } 

    @Override 
    public synchronized void onDestroy() { 
     super.onDestroy(); 
     Log.d(TAG, "onDestroy"); 
     if(!isRunning){ 
      mythread.interrupt(); 
      mythread.stop(); 
     }  
    } 

    @Override 
    public synchronized void onStart(Intent intent, int startId) { 
     super.onStart(intent, startId); 
     Log.d(TAG, "onStart"); 
     if(!isRunning){ 
      mythread.start(); 
      isRunning = true; 
     } 
    } 

    public void readWebPage(){ 
      HttpClient client = new DefaultHttpClient(); 
      HttpGet request = new HttpGet("http://google.com"); 
      // Get the response 
      ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
      String response_str = null; 
      try { 
      response_str = client.execute(request, responseHandler); 
      if(!response_str.equalsIgnoreCase("")){ 
       Log.d(TAG, "Got Response"); 
      } 
      } catch (Exception e) { 
      e.printStackTrace(); 
      } 
    } 

    class MyThread extends Thread{ 
     static final long DELAY = 3000; 
     @Override 
     public void run(){   
      while(isRunning){ 
       Log.d(TAG,"Running"); 
       try {     
        readWebPage(); 
        Thread.sleep(DELAY); 
       } catch (InterruptedException e) { 
        isRunning = false; 
        e.printStackTrace(); 
       } 
      } 
     } 

    } 

} 
+0

stop使用'isRunning = false; –

+0

hello sir我的查詢是mythred.start(),它是從onstart()方法的服務中觸發的,它每3秒延遲一次調用線程即run()方法。如何做到這一點,由於國旗檢查或一旦線程完成它返回到onstart()方法,它再次啓動線程或onstart方法本身返回一旦線程完成我沒有得到那.. – Viral

回答

0

OnStart方法被調用一次。 while循環正在重複(readWebPage())函數並在獲取響應表單服務器後停止線程只是給readWebPage()方法中的isRunnble變量賦值爲false

相關問題