Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 每隔5分钟通过后台服务在数据库中保存Lat long_Android_Database_Service - Fatal编程技术网

Android 每隔5分钟通过后台服务在数据库中保存Lat long

Android 每隔5分钟通过后台服务在数据库中保存Lat long,android,database,service,Android,Database,Service,我想每隔5分钟通过后端服务或数据库中的线程保存我当前的经度和纬度。然后我从db中检索所有lat长度并绘制其位置路径 我如何在安卓系统中做到这一点?这是我的代码: public class MyTestService extends IntentService { Intent i; TimerTask hourlyTask; Timer timer; Location location; // Must create a default constructor public MyTestSer

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

我如何在安卓系统中做到这一点?这是我的代码:

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();
    }

}

在活动中实现两个接口:ConnectionCallbacks、OnConnectionFailedListener,并执行以下操作以获得lat和long,希望它有所帮助

            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访问下面的文档链接


感谢rply@navin我得到lat long值主要问题是如何通过后台服务在数据库中插入这些值您可以使用ScheduledThreadPoolExecutor或其他选项查看ScheduledThreadPoolExecutor示例代码中的我的编辑,但您也可以使用AlarmManager或Timer。我是初学者,如果与大家分享,我将非常感谢完成此操作的完整代码I am Get error“方法不重写或实现超类型中的方法”@NavinRajPandey我也在使用FusedLocationAPI我的问题是当我停止服务并启动新服务时它崩溃了。它给我的是谷歌的客户端,但它还没有连接。我试过了,但没有成功。。那么你能再次更新你的问题吗?