2013-04-09 63 views
-9

我將使用下面的代碼獲取Android設備的經緯度,但我希望每15分鐘更新一次緯度和經度。我怎樣才能得到這個?每15分鐘撥打一次電話的方法

package com.position.position; 

    import java.io.BufferedReader; 
    import java.io.InputStream; 
    import java.io.InputStreamReader; 
    import java.util.ArrayList; 
    import java.util.List; 
    import java.util.Timer; 
    import java.util.TimerTask; 

    import org.apache.http.HttpEntity; 
    import org.apache.http.HttpResponse; 
    import org.apache.http.NameValuePair; 
    import org.apache.http.client.HttpClient; 
    import org.apache.http.client.entity.UrlEncodedFormEntity; 
    import org.apache.http.client.methods.HttpPost; 
    import org.apache.http.impl.client.DefaultHttpClient; 
    import org.apache.http.message.BasicNameValuePair; 

    import android.app.Activity; 
    import android.content.Context; 
    import android.location.Location; 
    import android.location.LocationManager; 
    import android.os.Bundle; 
    import android.os.Handler; 
    import android.os.Looper; 
    import android.os.Message; 
    import android.util.Log; 
    import android.view.Menu; 
    import android.view.View; 
    import android.view.View.OnClickListener; 
    import android.widget.Button; 
    import android.widget.EditText; 
    import android.widget.TextView; 
    import android.widget.Toast; 

    public class Main extends Activity { 
     StringBuilder stringBuilderlatitude = new StringBuilder(); 
     StringBuilder stringBuilderlongitude = new StringBuilder(); 
     public EditText NombreSeconde; 
     public EditText NombreMetre; 
     public float ValueNM; 
     public int i=0; 
     LocationManager locationManager; 
     private String locationProvider = LocationManager.GPS_PROVIDER; 
     float numberMetre; 
     @Override 
     protected void onCreate(Bundle savedInstanceState) {   
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.main); 
      Button BtnValider = (Button)findViewById(R.id.BtnValider); 

      BtnValider.setOnClickListener(new OnClickListener() { 

       @Override 

       public void onClick(View v) { 

        NombreSeconde = (EditText) findViewById(R.id.ValeurSeconde); 
        EditText NombreMetreEditText = (EditText) findViewById(R.id.ValeurMetre); 
        numberMetre = Float.valueOf(NombreMetreEditText.getText().toString()); 
Toast.makeText(getApplicationContext(), "Paramètres enregistrés", Toast.LENGTH_SHORT).show(); 


       } 

       }); 

      ///////////////////////////////////// 
      String locationContext = Context.LOCATION_SERVICE; 
      locationManager = (LocationManager) getSystemService(locationContext); 
      //majCoordonnes(); 

locationManager.requestLocationUpdates(locationProvider,100100,新MajListener());

 } 
     /////////////////////////// 

     ////////////////////////// 
     class MajListener implements android.location.LocationListener { 
      public void onLocationChanged(Location location) { 
       stringBuilderlatitude= new StringBuilder(); 
       stringBuilderlongitude=new StringBuilder(); 


       majCoordonnes(); 


      } 
      public void onProviderDisabled(String provider){ 
      } 
      public void onProviderEnabled(String provider){ 
      } 
      public void onStatusChanged(String provider, int status, Bundle extras){ 
      } 


     }; 

     public void majCoordonnes() { 
      Toast.makeText(getApplicationContext(), "Mise à jour des coordonnées",200000).show(); 

      StringBuilder stringBuilder = new StringBuilder(); 
      stringBuilder.append("Fournisseurs :"); 
      List<String> providers = locationManager.getProviders(true); 
      // Pour chaque fournisseur ... 
      for (String provider : providers) { 
       stringBuilder.append("\n"); 
       stringBuilder.append(provider); 
       stringBuilder.append(" : "); 
       // ... on affiche la position. 
       Location location = locationManager.getLastKnownLocation(provider); 
       String locationContext = Context.LOCATION_SERVICE; 
       locationManager = (LocationManager) getSystemService(locationContext); 
       if (location != null) { 
        double latitude = location.getLatitude(); 
        double longitude = location.getLongitude(); 
        stringBuilder.append(latitude); 
        stringBuilder.append(", "); 
        stringBuilder.append(longitude); 
       } else { 
        stringBuilder.append("Non déterminée"); 
       } 
      } 

      // Log.i("MaPosition", stringBuilder.toString()); 
      TextView t=new TextView(this); 
      t=(TextView)findViewById(R.id.TextResultat); 
      t.setText(stringBuilder.toString()); 


      ///////////////////////////////////// partie ajoute////////////////////////// 
      LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
      Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
      double longitude = location.getLongitude(); 
      double latitude = location.getLatitude(); 


      stringBuilderlatitude.append(latitude); 
      stringBuilderlongitude.append(longitude); 


      String xlatitude=stringBuilderlatitude.toString(); 
      String xLongitude=stringBuilderlongitude.toString(); 

      Log.i("MaPosition","x1="+xlatitude +"x2="+ xLongitude); 

      //Log.i("MaPosition", " apres append"+stringBuilderlatitude.toString()); 
      String y=stringBuilderlongitude.toString(); 
      stringBuilderlongitude.append(longitude); 
      String result = ""; 
      ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
      //nameValuePairs.add(new BasicNameValuePair("year","1980"));   
      try{ 
       Log.i("MaPosition", "Envoi les coordonnes au serveur"); 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost("http://www.kbma.site.com/insertGPS.php?latitude="+xlatitude.toString()+"&longitude="+xLongitude); 
        Toast.makeText(getApplicationContext(), "Coordonnes envoyées au serveur kbma.site.com",200000).show(); 
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
        HttpResponse response = httpclient.execute(httppost); 
        HttpEntity entity = response.getEntity(); 
        InputStream is = entity.getContent(); 
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
        StringBuilder sb = new StringBuilder(); 
        String line = null; 
        while ((line = reader.readLine()) != null) { 
          sb.append(line + "\n"); 
        } 
        is.close(); 

        result=sb.toString(); 

      } 
      catch(Exception e){ 
        Log.i("log_tag", "Error in http connection "+e.toString()); 
      } 

     } 
     ///////////////////////// 

     ///////////////// 

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

    } 
+6

哇的......你剛纔轉儲**這192行代碼中的所有**。如果你只是給我們所有的代碼並說「修復它」,沒有人會提供幫助! – Doorknob 2013-04-09 21:12:36

+0

也許你想在Activity中使用Locatoin Poller。訪問https://github.com/commonsguy/cwac-locpoll並享受樂趣。 – 2013-04-09 21:14:50

+0

AlarmManager - http://developer.android.com/reference/android/app/AlarmManager.html – Squonk 2013-04-09 21:15:09

回答

1

此代碼更新的位置每5秒(15 * 60 * 1000毫秒)或500計:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, (15 * 60 * 1000), 500, locationListener); 
LocationListener locationListener = new MyLocationListener(); 

// ... 

public class MyLocationListener implements LocationListener { 

    public void onLocationChanged(Location location) { 
     currentLocation = new GeoPoint(location); 
     // ... 
    } 

    public void onProviderDisabled(String provider) { 
    } 

    public void onProviderEnabled(String provider) { 
    } 

    public void onStatusChanged(String provider, int status, Bundle extras) { 
    } 
} 
2

您已經從系統請求位置更新,只是增加的時間頻率從100毫秒到15分鐘。改變這一行:

locationManager.requestLocationUpdates(locationProvider,100,100, new MajListener()); 

這樣:

locationManager.requestLocationUpdates(locationProvider,(15 * 60 * 1000),100, new MajListener()); 

還要注意的是,因爲你是你要停止獲取回調,當用戶導航從遠離活動的活動內。

如果你想這對在後臺運行(因此不會被關閉,當用戶導航離開),你需要把它變成一個服務,而不是一個活動