2017-07-08 6 views
0

Ich möchte alle 10 Minuten einen Standort verfolgen und ihn über die asynchrone TraceDelivery-Task an den Server senden. Dafür habe ich versucht, einen Dienst und einen Timer zu verwenden, um den Standort alle 10 Minuten zu bekommen.Der Timer wird nicht zur geplanten Zeit angerufen.

Aber wenn ich von einer anderen Aktivität den Dienst anrufe, funktioniert es nur einmal, d. H. Sobald TraceDelivery api aufgerufen wird, aber nicht wieder. Zum Testen habe ich nur eine zweite Verzögerung gegeben, aber es wird nicht wieder aufgerufen.

Auch wenn ich überprüfe, ob mlaatLang null ist und dann die TraceDelivery aufrufen, wurde es nicht mindestens einmal aufgerufen. Wenn location jedoch null ist, wird es mit einem Null-Zeiger auf mlaatLang abgestürzt.

Servicecode:

public class LocationTrackerService extends IntentService implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{ 

    private Handler handler; 
    private Timer timer; 
    private TimerTask timerTask; 
    private GoogleApiClient mGoogleApiClient; 
    Location mLastLocation; 
    private LatLng mLatLang; 
    LocationManager mLocationManager = null; 
    boolean gps_enabled = false; 
    boolean network_enabled = false; 


    LocationListener[] mLocationListeners = new LocationListener[]{ 
      new LocationListener(LocationManager.NETWORK_PROVIDER), 
      new LocationListener(LocationManager.GPS_PROVIDER) 

    }; 

    /** 
    * A constructor is required, and must call the super IntentService(String) 
    * constructor with a name for the worker thread. 
    */ 
    public LocationTrackerService() { 
     super("HelloIntentService"); 
    } 

    /** 
    * 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 
    protected void onHandleIntent(Intent intent) { 
     // Normally we would do some work here, like download a file. 
     // For our sample, we just sleep for 5 seconds. 
     try { 
      Thread.sleep(1000); 

      buildGoogleApiClient(); 
      mGoogleApiClient.connect(); 

      handler = new Handler(); 

       initializeLocationManager(); 
       requestLocation(); 


       startTimer(intent.getStringExtra("dl_id"), intent.getStringExtra("pt_id"), intent.getStringExtra("ur_id"),intent.getStringExtra("address"), 
         intent.getStringExtra("api_key")); 


     } catch (InterruptedException e) { 
      // Restore interrupt status. 
      Thread.currentThread().interrupt(); 
     } 
    } 
    public void startTimer(String dlId,String ptId,String urId,String add,String key) { 
     //set a new Timer 
     timer = new Timer(); 

     //initialize the TimerTask's job 
     initializeTimerTask(dlId, ptId, urId,key); 

     //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms 
     timer.schedule(timerTask, 1000, 1000);// 
    } 

    public void initializeTimerTask(final String dlId, final String ptId, final String urId, final String key) { 

     timerTask = new TimerTask() { 
      public void run() { 

       //use a handler to run a toast that shows the current timestamp 
       handler.post(new Runnable() { 
        public void run() { 

          TraceDeliveryAsyncTask traceDeliveryAsyncTask = new TraceDeliveryAsyncTask(LocationTrackerService.this); 
          traceDeliveryAsyncTask.execute(dlId, ptId, urId, String.valueOf(mLatLang.latitude), 
            String.valueOf(mLatLang.longitude),"", key); 

          Log.e("timer","success"); 


        } 
       }); 
      } 
     }; 
    } 

    public void stoptimertask() { 
     //stop the timer, if it's not already null 
     if (timer != null) { 
      timer.cancel(); 
      timer = null; 
     } 
    } 

    protected synchronized void buildGoogleApiClient() { 

     mGoogleApiClient = new GoogleApiClient.Builder(LocationTrackerService.this) 
       .addConnectionCallbacks(LocationTrackerService.this) 
       .addOnConnectionFailedListener(LocationTrackerService.this) 
       .addApi(LocationServices.API) 
       .build(); 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     // Toast.makeText(getActivity(),"onConnected",Toast.LENGTH_SHORT).show(); 

    } 

    @Override 
    public void onConnectionSuspended(int i) { 
     // Toast.makeText(getActivity(),"onConnectionSuspended",Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     // Toast.makeText(getActivity(),"onConnectionFailed",Toast.LENGTH_SHORT).show(); 
    } 

    private void initializeLocationManager() { 
     // Log.e(Application.TAG, "initializeLocationManager"); 
     if (mLocationManager == null) { 
      mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     } 

     try { 
      gps_enabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
     } catch (Exception ex) { 
     } 

     try { 
      network_enabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
     } catch (Exception ex) { 
     } 

     if (!gps_enabled && !network_enabled) { 
      // notify user 
      if(!CommonUtils.isGPSEnabled(getApplicationContext())) 
       startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
     } 

    } 

    public class LocationListener implements android.location.LocationListener { 

     public LocationListener() { 
     } 

     public LocationListener(String provider) { 
      Log.e(TAG, "LocationListener " + provider); 
      mLastLocation = new Location(provider); 
     } 

     @Override 
     public void onLocationChanged(Location location) { 
      Log.e(TAG, "onLocationChanged: " + location); 

      //get current location 

      if(mLastLocation != null && !mLastLocation.equals("")) { 
       mLastLocation.set(location); 
       mLatLang = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()); 
      } 
      else { 

      } 

     } 

     @Override 
     public void onProviderDisabled(String provider) { 
      Log.e(TAG, "onProviderDisabled: " + provider); 

     } 

     @Override 
     public void onProviderEnabled(String provider) { 
      Log.e(TAG, "onProviderEnabled: " + provider); 

     } 

     @Override 
     public void onStatusChanged(String provider, int status, Bundle extras) { 
      Log.e(TAG, "onStatusChanged: " + provider); 
     } 
    } 

    //request for location, first by network, then by gps 

    public void requestLocation() { 

     try { 
      mLocationManager.requestLocationUpdates(
        LocationManager.NETWORK_PROVIDER, 0, 0, 
        mLocationListeners[0]); 
     } catch (java.lang.SecurityException ex) { 
      Log.i(TAG, "fail to request location update, ignore", ex); 
     } catch (IllegalArgumentException ex) { 
      Log.d(TAG, "network provider does not exist, " + ex.getMessage()); 
     } 

     try { 
      mLocationManager.requestLocationUpdates(
        LocationManager.GPS_PROVIDER, 0, 0, 
        mLocationListeners[1]); 
     } catch (java.lang.SecurityException ex) { 
      Log.i(TAG, "fail to request location update, ignore", ex); 
     } catch (IllegalArgumentException ex) { 
      Log.d(TAG, "gps provider does not exist " + ex.getMessage()); 
     } 
    } 

} 

Wie kann ich das erreichen? Bitte helfen Sie mit this.Thank Sie ..

Antwort

1

IntentService gesucht haben Stoppen Sie sofort eine ist die Aufgabe in OnHandleIntent,

So statt IntentService versuchen, Service für lange laufende Operationen zu verwenden.

1

Die Android-Alarmmanager-Klasse eine Absicht in festgelegten Intervallen an Ihre Anwendung gesendet werden auslösen können, und führen Sie die definierte task.Probably, was Sie werden für

Verwandte Themen