每隔5分钟通过后台服务在数据库中保存Lat长时间

时间:2020-12-10 01:26:04

I want to save my current longitude and latitude through backend service or thread in database after every 5 minutes interval. Then I retrive all the lat long from db and draw its location path.

每隔5分钟,我想通过后端服务或数据库中的线程保存当前的经度和纬度。然后我从db中获取所有lat,并绘制它的位置路径。

How can I do this in android? This is my code:

我如何在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 个解决方案

#1


2  

implement two interfaces : ConnectionCallbacks, OnConnectionFailedListener with your activity and do the following to get lat and long hope it helps .

实现两个接口: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);

// another way is using alarm manager visit documentation link below

//另一种方法是使用警报管理器访问文档链接

Alarm Manager documentation

报警管理文档

#1


2  

implement two interfaces : ConnectionCallbacks, OnConnectionFailedListener with your activity and do the following to get lat and long hope it helps .

实现两个接口: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);

// another way is using alarm manager visit documentation link below

//另一种方法是使用警报管理器访问文档链接

Alarm Manager documentation

报警管理文档