2013-03-12 79 views
1

我已經創建了一個應用程序,它將用戶位置發送到服務器..並且它使用異步任務(doInBackground和onPostExecute方法)在後臺運行...但它運行速度非常慢..在編碼中我使用了Thread.sleep(300000)爲間隔5分鐘...我認爲應用程序停止運行..Android:如何在後臺永遠運行應用程序?

YasarKhan.java

Location location; // location 
    double latitude; // latitude 
    double longitude; // longitude 

    // The minimum distance to change Updates in meters 
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000; // 1000 
                     // meters 

    // The minimum time between updates in milliseconds 
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 20; // 20 minute 

    // Declaring a Location Manager 
    protected LocationManager locationManager; 
    boolean done = true; 

// public YasarKhan(Context context) { 
//  this.mContext = context; 
//  
// 
// } 



    public void gpsTraking() { 

     // check if GPS enabled 
     if (true) { 
      stAdd = ""; 
      double latitude = getLatitude(); 
      double longitude = getLongitude(); 
      Geocoder gc = new Geocoder(getBaseContext()); 
      try 
      { 
       List<Address> list = gc.getFromLocation(latitude, longitude, 2); 
       Address a = list.get(0); 
       for (int i = 0; i <= a.getMaxAddressLineIndex(); i++) { 
        stAdd = stAdd + "\n " + a.getAddressLine(i); 
       } 
       stAdd = stAdd + " " + a.getLocality() + "\n" 
         + a.getFeatureName(); 

      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 


    } 

    public void passing() 
    { 
     new SendFeedback().execute(imei,simSerialNumber,stAdd,currentTime); 
    } 


    class SendFeedback extends AsyncTask<String, Void, String> 
    { 
     @Override 
     protected String doInBackground(String... paramArrayOfParams) 
     { 
      SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
      request.addProperty("strIMEINumber", paramArrayOfParams[0]); 
      request.addProperty("strSIMNumber", paramArrayOfParams[1]);  
      request.addProperty("strAddress", paramArrayOfParams[2]); 
      request.addProperty("strTime", paramArrayOfParams[3]); 

      SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
      envelope.dotNet = true; 
      envelope.encodingStyle = SoapSerializationEnvelope.ENC; 
      envelope.setOutputSoapObject(request); 
      System.setProperty("http.keepAlive", "false"); 

      try 
      { 
       HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); 
       androidHttpTransport.call(SOAP_ACTION, envelope); 
       // SoapObject result = (SoapObject) envelope.getResponse(); 
       SoapPrimitive response = (SoapPrimitive) envelope.getResponse(); 
       String resultData = response.toString(); 
       Log.d("response", resultData); 
       return resultData;    
      } 
      catch (Exception e) 
      { 
       Log.d("My Error", "" + e.getMessage()); 

      } 
      return resultData; 
     } 

     @Override 
     protected void onPostExecute(String result) 
     { 
      Log.d("strResult", result); 
      super.onPostExecute(result); 
     } 
    } 
} 

MyReceiver.java

package com.example.yasar; 

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.util.Log; 

public class MyReceiver extends BroadcastReceiver { 


     public static final String TAG = "com.example.gpstraking"; 
     @Override 
     public void onReceive(Context context, Intent intent) 
     { 

      try 
      { 

       Intent serviceIntent = new Intent(context, YasarKhan.class); 
       context.startService(serviceIntent);  
      } 
      catch(Exception e) 
      { 
       Log.e("My Service Error",e.getMessage()); 
      } 


     } 



} 

MainActivity.java

package com.example.yasar; 

import android.os.Bundle; 
import android.app.Activity; 
import android.content.Intent; 
import android.util.Log; 
import android.view.Menu; 

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     Log.d("naveeeen","kushwaaahaACTIVITY"); 
     Intent serviceIntent = new Intent(this, YasarKhan.class); 
     this.startService(serviceIntent); 

    } 



    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     //getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 
    } 

} 
+0

我想這裏的DVM可以不負責這些asnyc任務的終止,如果它的設備正在測試中,確保沒有第三方應用程序(任務殺手)安裝,因爲他們通常運行現在每隔n周清理一次,然後嘗試使用等待通知,而不是永遠與睡眠同時循環。 – 2013-03-12 07:12:10

+0

Thread.sleep(300000);使用這將產生不準確的睡眠/延遲 – Kiran 2013-03-12 07:16:36

+1

stack_ved:我如何使用等待,而不是睡覺,而方法....我將檢查有關清理 – 2013-03-12 10:04:16

回答

2

使用的服務,在onStartCommand():

  1. 使用requestLocationUpdates。

    locationManager.requestLocationUpdates(provider, 5000, 0, myLocationListener); 
    
  2. 調用此方法來檢查供應商在onStartCommand()

    public void testProviders() 
        { 
         //Choose only one provider      
         Location location = locationManager.getLastKnownLocation(provider);  
         if (location != null) 
         { 
          lat = location.getLatitude(); 
          lng = location.getLongitude(); 
          str = "Test Provider method says :"+" Latitude = " +lat + " and " + " Longitude = " +lng; 
          System.err.println("Current Latitude and Longitude:"+lat+","+lng); 
    
         }     
         else 
         { 
          str = " No Location "; 
         } 
         System.err.println(str); 
         Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show(); 
        } 
    
  3. 使用監聽

    LocationListener myLocationListener = new LocationListener() 
        { 
    
         @Override 
         public void onLocationChanged(Location location) 
         { 
          if (location != null) 
          { 
           Clat = location.getLatitude(); 
           Clng = location.getLongitude();   
           System.out.println("Change latitude and Longitude:"+Clat+", "+Clng+"timer: " +System.currentTimeMillis());       
           String str = " LocationListener : Change latitude and Longitude: " +Clat+ ", " +Clng+ " timer: " +System.currentTimeMillis(); 
           System.err.println(str); 
           Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show(); 
           new SendPGLocationToServer().execute(); 
          } 
          else 
          { 
           str = " No Location. "; 
           Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show(); 
          } 
         } 
    
  4. ,最後,使用的AsyncTask送位置到服務器。

+0

Manish:我幾乎做了同樣的事情...在logcat中:ANR沒有響應..SSL異常...找不到可信的證書 – 2013-03-13 09:39:12

相關問題