2016-08-29 40 views
0

我希望每間隔5分鐘後通過後端服務或數據庫中的線程保存當前的經度和緯度。然後我從數據庫中搜索所有lat,並繪製它的位置路徑。每間隔5分鐘後通過後臺服務將緯度保存在數據庫中

我該如何在android中做到這一點?這是我的代碼:

public class MyTestService extends IntentService { 
Intent i; 
TimerTask hourlyTask; 
Timer timer; 
Location location; 

// Must create a default constructor 
public MyTestService() { 
    // Used to name the worker thread, important only for debugging. 
    super("test-service"); 
} 

@Override 
public void onCreate() { 
    super.onCreate(); // if you override onCreate(), make sure to call super(). 
    // If a Context object is needed, call getApplicationContext() here. 
    onHandleIntent(i); 
} 


@Override 
protected void onHandleIntent(Intent intent) { 
    timer = new Timer(); 
    hourlyTask = new TimerTask() { 
     @Override 
     public void run() { 
      onHandleIntent(i); 
     } 
    }; 

// schedule the task to run starting now and then every hour... 
    timer.schedule(hourlyTask, 0l, 1000*5*60); // 1000*10*60 every 10 minut 

    SQLiteDatabase db; 
    db = openOrCreateDatabase("Temp.db", SQLiteDatabase.CREATE_IF_NECESSARY, null); 
    try { 
     final String CREATE_TABLE_CONTAIN = "CREATE TABLE IF NOT EXISTS tbl_Contain (" 
       + "ID INTEGER primary key AUTOINCREMENT," 
       + "DESCRIPTION TEXT," 
       + "expirydate DATETIME," 
       + "AMOUNT TEXT," 
       + "TRNS TEXT," + "isdefault TEXT);"; 
     db.execSQL(CREATE_TABLE_CONTAIN); 
     Toast.makeText(getApplicationContext(), "table created ", Toast.LENGTH_LONG).show(); 
     String sql = 
       "INSERT or replace INTO tbl_Contain (DESCRIPTION, expirydate, AMOUNT, TRNS,isdefault) VALUES('farhan','03/04/2005','5000','ali','y')"; 
     db.execSQL(sql); 
     Toast.makeText(getApplicationContext(), "inserted", Toast.LENGTH_LONG).show(); 

    } 
    catch (Exception e) 
    { 
     Toast.makeText(getApplicationContext(), "ERROR " + e.toString(), Toast.LENGTH_LONG).show(); 
    } 

} 

回答

1

實現兩個接口:ConnectionCallbacks,OnConnectionFailedListener與活動並執行以下操作來獲得lat和長希望它幫助。

  String lat=""; 
      String longi="";    
      GoogleApiClient mGoogleApiClient; 
      Location mLastLocation; 
      LocationListener mLocationListener; 

      // method to create connection with GoogleApiClinet 

      protected synchronized void buildGoogleApiClient() { 
       mGoogleApiClient = new GoogleApiClient.Builder(this) 
         .addConnectionCallbacks(this) 
         .addOnConnectionFailedListener(this) 
         .addApi(LocationServices.API) 
         .build(); 
      } 

    //method to request user to on location 
      public void forLocation(){ 


       LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE); 
       boolean gps_enabled = false; 
       boolean network_enabled = false; 

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

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

       if(!gps_enabled && !network_enabled) { 
        // notify user 
        AlertDialog.Builder dialog = new AlertDialog.Builder(this); 
        dialog.setMessage("GPS not enabled"); 
        dialog.setPositiveButton("Open location settings", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface paramDialogInterface, int paramInt) { 

          Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
          HomeActivity.this.startActivity(myIntent); 
          //get gps 
         } 
        }); 
        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 

         @Override 
         public void onClick(DialogInterface paramDialogInterface, int paramInt) { 
          // TODO Auto-generated method stub 

         } 
        }); 
        dialog.show(); 
       } 

      } 

    // inside onCreate method 


      forLocation(); 
      buildGoogleApiClient(); 
      if(mGoogleApiClient!= null){ 
       mGoogleApiClient.connect(); 
      } 
      else{ 
       Toast.makeText(this, "Not connected...", Toast.LENGTH_SHORT).show(); 
      } 
//override two methods in your activity 

@Override 
    public void onConnected(Bundle arg0) { 

     mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
       mGoogleApiClient); 

     if (mLastLocation != null) { 
      //System.out.println("Latitude--------------------------------->: "+ String.valueOf(mLastLocation.getLatitude())+"Longitude: "+ 
        String.valueOf(mLastLocation.getLongitude()); 

      lat=String.valueOf(mLastLocation.getLatitude()); 
      longi=String.valueOf(mLastLocation.getLongitude()); 

     } 

    } 

    @Override 
    public void onConnectionSuspended(int arg0) { 
     Toast.makeText(this, "Connection suspended...", Toast.LENGTH_SHORT).show(); 

    } 
// user ScheduledThreadPoolExecutor to repeatedly insert data into database 

ScheduledExecutorService scheduler = 
    Executors.newSingleThreadScheduledExecutor(); 

scheduler.scheduleAtFixedRate 
     (new Runnable() { 
     public void run() { 
      // call database insertion service here 
     } 
     }, 0, 10, TimeUnit.MINUTES); 

//另一種方法是使用

Alarm Manager documentation

+0

感謝rply低於警報管理器訪問文檔鏈接@navin我得到緯度長值主要問題是,如何在DB通過後臺插入這些值服務 –

+0

你可以使用ScheduledThreadPoolExecutor或其他選項在ScheduledThreadPoolExecutor例子的代碼中看到我的編輯,但你也可以使用AlarmManager或Timer。 –

+0

什麼是ScheduledThreadPoolExecutor –

相關問題