Android 如何在mysql数据库中每10秒更新一次经纬度?

Android 如何在mysql数据库中每10秒更新一次经纬度?,android,Android,我正在尝试从Android设备获取纬度和经度,并将其发送到MySQL数据库。当任何人注册其当前保存在数据库中的纬度和经度时。但我想知道如何每10秒更新保存的纬度和经度。以下是我的代码: public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnCon

我正在尝试从Android设备获取纬度和经度,并将其发送到MySQL数据库。当任何人注册其当前保存在数据库中的纬度和经度时。但我想知道如何每10秒更新保存的纬度和经度。以下是我的代码:

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener, GoogleMap.OnCameraMoveListener {

    GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    double latitude, longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);

    }

    @Override
    public void onPause() {
        super.onPause();


        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {


        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        mGoogleMap.clear();

        latitude = location.getLatitude();
        longitude = location.getLongitude();


        LatLng latLng = new LatLng(latitude, longitude);

        MarkerOptions markerOptions = new MarkerOptions();

        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
        mCurrLocationMarker.setPosition(latLng);
        CameraPosition liberty = CameraPosition.builder().target(new LatLng(latitude, longitude)).zoom(15.5f).bearing(0).tilt(45).build();
        mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(liberty));


        Intent intent = new Intent(MainActivity.this, Register.class);

        intent.putExtra("Latitude", latitude);
        intent.putExtra("Longitude", longitude);
        startActivity(intent);

        callAsynchronousTask();

        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));


    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {


            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {


                new AlertDialog.Builder(this)
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                ActivityCompat.requestPermissions(MainActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION);
                            }
                        })
                        .create()
                        .show();


            } else {

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        mGoogleMap = googleMap;
        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);


        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {

                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);
            } else {

                checkLocationPermission();
            }
        } else {
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        }
    }

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

    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {

                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {

                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

        }
    }

    @Override
    public void onCameraMove() {

        mCurrLocationMarker.setPosition(mGoogleMap.getCameraPosition().target);

    }

    public void callAsynchronousTask() {
        final Handler handler = new Handler();
        Timer timer = new Timer();
        TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        try {
                            Register performBackgroundTask = new Register();

                            performBackgroundTask.onSupportContentChanged();
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                        }
                    }
                });
            }
        };
        timer.schedule(doAsynchronousTask, 0, 50000);
    }
}

Register class:-

public class Register extends AppCompatActivity {

    EditText name_txt, email_txt, mobile_txt;
    String getname, getemail, getmobilenumber;
    Button upload, register;
    TextView image_text;
    TypedFile avatarFile1 = null;
    String picturePath = "";
    private String userChoosenTask;
    private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
    File uri;
    double getlatitude;
    double getlongitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        Find_view_by_id();
        Bundle extras = getIntent().getExtras();
        getlatitude = extras.getDouble("Latitude");
        getlongitude = extras.getDouble("Longitude");


        Toast.makeText(this, "Your Location is - \nLat: " + getlatitude + "\nLong: " + getlongitude, Toast.LENGTH_SHORT).show();
    }

    private void Find_view_by_id() {

        name_txt = (EditText) findViewById(R.id.name);
        email_txt = (EditText) findViewById(R.id.email);
        mobile_txt = (EditText) findViewById(R.id.mobilenumber);
        upload = (Button) findViewById(R.id.upload_image);
        image_text = (TextView) findViewById(R.id.upload_image_text);
        register = (Button) findViewById(R.id.register);

        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage();
            }
        });

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getname = name_txt.getText().toString();
                getemail = email_txt.getText().toString();
                getmobilenumber = mobile_txt.getText().toString();

                if (getname.trim().equalsIgnoreCase("")) {
                    name_txt.setError("Please Enter First Name");
                    name_txt.requestFocus();

                } else if (getemail.trim().equalsIgnoreCase("")) {
                    email_txt.setError("Please Enter email address");
                    email_txt.requestFocus();
                } else if (!getemail.matches("[a-zA-Z0-9._-]+@[a-z]+.[a-z]+")) {
                    email_txt.setError("Please Enter valid  email address");
                    email_txt.requestFocus();
                } else if (getmobilenumber.trim().equalsIgnoreCase("")) {

                    mobile_txt.setError("Please enter mobile number");
                    mobile_txt.requestFocus();
                } else if (getmobilenumber.length() < 10) {
                    mobile_txt.setError("Please Enter correct mobile number");
                    mobile_txt.requestFocus();
                } else {
                    Register_user(getname, getemail, getmobilenumber, picturePath, getlatitude, getlongitude);
                }
            }

            private void Register_user(String name, String email, String mobilenumber, String avatarFile, Double latitud_e, Double longitud_e) {

                if (avatarFile != null) {
                    avatarFile1 = new TypedFile("image/*", new File(String.valueOf(avatarFile)));
                }

                RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(Constant.constant).build();
                Register_API registerapi = restAdapter.create(Register_API.class);

                registerapi.getuser(name, email, mobilenumber, avatarFile1, latitud_e, longitud_e, new Callback<RegisterModel>() {
                    @Override
                    public void success(RegisterModel registerModel, Response response) {

                        Long status = registerModel.getSuccess();

                        if (status == 1) {

                            name_txt.setText("");
                            email_txt.setText("");
                            mobile_txt.setText("");
                            image_text.setText("");
                            Toast.makeText(Register.this, "Successful ", Toast.LENGTH_SHORT).show();

                            Intent i = new Intent(Register.this, Show_List_Activity.class);
                            startActivity(i);
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {

                        Toast.makeText(Register.this, "Failure ", Toast.LENGTH_SHORT).show();

                    }
                });
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (userChoosenTask.equals("Take Photo"))
                        cameraIntent();
                    else if (userChoosenTask.equals("Choose from Library"))
                        galleryIntent();
                } else {

                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_FILE) {
                onSelectFromGalleryResult(data);
            } else if (requestCode == REQUEST_CAMERA) {
                Log.e("log path", "" + uri);
                String myImagename = getImageName(String.valueOf(uri));
                image_text.setText(myImagename);
            }

        }

    }


    private String getImageName(String picturePath) {
        String Imagename = null;

        String[] name_array = picturePath.split("/");
        Log.e("size of array", "" + name_array.length);

        Imagename = name_array[name_array.length - 1];

        Log.e("name of image", "" + Imagename);

        return Imagename;
    }

    private void selectImage() {

        final CharSequence[] items = {"Take Photo", "Choose from Library",
                "Cancel"};

        AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                boolean result = Utility.checkPermission(Register.this);

                if (items[item].equals("Take Photo")) {
                    userChoosenTask = "Take Photo";
                    if (result)
                        cameraIntent();

                } else if (items[item].equals("Choose from Library")) {
                    userChoosenTask = "Choose from Library";
                    if (result)
                        galleryIntent();

                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    private void galleryIntent() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(intent, SELECT_FILE);
    }

    private void cameraIntent() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        uri = getOutputMediaFile(MEDIA_TYPE_IMAGE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, REQUEST_CAMERA);

    }

    private static File getOutputMediaFile(int type) {

        File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/.Dope/");

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {

                return null;
            }
        }

        File mediaFile;
        java.util.Date date = new java.util.Date();
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir, Long.toString(System.currentTimeMillis()) + "IMG_" + new Timestamp(date.getTime()).toString() + ".jpg");
        } else {
            return null;
        }
        return mediaFile;
    }

    @SuppressWarnings("deprecation")
    private void onSelectFromGalleryResult(Intent data) {

        Bitmap bm = null;
        if (data != null) {

            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};


            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();

            String myimagename = getImageName(picturePath);

            image_text.setText(myimagename);


        }


    }
}
public类MainActivity扩展了AppCompatActivity在MapreadyCallback上的实现,
GoogleAppClient.ConnectionCallbacks,
GoogleAppClient.OnConnectionFailedListener,
LocationListener,GoogleMap.OnCameraMoveListener{
谷歌地图;
支持mapFrag;
位置请求mLocationRequest;
GoogleapClient MGoogleapClient;
位置mLastLocation;
标记器mCurrLocationMarker;
双纬度,经度;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFrag=(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
getMapAsync(这个);
}
@凌驾
公共无效暂停(){
super.onPause();
if(mGoogleApiClient!=null){
LocationServices.FusedLocationApi.RemovelocationUpdate(mgoogleapClient,this);
}
}
@凌驾
未连接的公共无效(@Nullable Bundle){
mlLocationRequest=新位置请求();
mlLocationRequest.setInterval(1000);
mlLocationRequest.setFastTestInterval(1000);
mLocationRequest.setPriority(位置请求.优先级高精度);
如果(ContextCompat.checkSelfPermission)(此,
清单.权限.访问(位置)
==PackageManager.权限(已授予){
LocationServices.FusedLocationApi.RequestLocationUpdate(mgoogleapClient、mlLocationRequest、this);
}
}
@凌驾
公共空间连接暂停(int i){
}
@凌驾
public void onconnection失败(@NonNull ConnectionResult ConnectionResult){
}
@凌驾
已更改位置上的公共无效(位置){
mLastLocation=位置;
if(mCurrLocationMarker!=null){
mCurrLocationMarker.remove();
}
mGoogleMap.clear();
纬度=位置。getLatitude();
longitude=location.getLongitude();
LatLng LatLng=新LatLng(纬度、经度);
MarkerOptions MarkerOptions=新MarkerOptions();
标记选项位置(板条);
标记选项。标题(“当前位置”);
mCurrLocationMarker=mGoogleMap.addMarker(markerOptions);
MCURLOCATIONMARKER.设定位置(板条);
CameraPosition liberty=CameraPosition.builder().target(新LatLng(纬度、经度)).zoom(15.5f).方位(0).倾斜(45).build();
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(liberty));
意向意向=新意向(MainActivity.this、Register.class);
意图。putExtra(“纬度”,纬度);
intent.putExtra(“经度”,经度);
星触觉(意向);
callAsynchronousTask();
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
}
公共静态final int MY_PERMISSIONS_REQUEST_LOCATION=99;
私有void checkLocationPermission(){
if(ContextCompat.checkSelfPermission(这个,Manifest.permission.ACCESS\u FINE\u位置)
!=PackageManager.权限(已授予){
如果(活动公司)应显示请求许可理由(此,
清单.权限.访问(位置){
新建AlertDialog.Builder(此)
.setTitle(“需要位置许可”)
.setMessage(“此应用程序需要位置权限,请接受以使用位置功能”)
.setPositiveButton(“确定”,新的DialogInterface.OnClickListener(){
@凌驾
公共void onClick(DialogInterface,inti){
ActivityCompat.requestPermissions(MainActivity.this,
新字符串[]{Manifest.permission.ACCESS\u FINE\u LOCATION},
我的\权限\请求\位置);
}
})
.create()
.show();
}否则{
ActivityCompat.requestPermissions(此,
新字符串[]{Manifest.permission.ACCESS\u FINE\u LOCATION},
我的\权限\请求\位置);
}
}
}
@凌驾
4月1日公开作废(谷歌地图谷歌地图){
mGoogleMap=谷歌地图;
mGoogleMap.setMapType(GoogleMap.MAP\u TYPE\u HYBRID);
if(android.os.Build.VERSION.SDK\u INT>=Build.VERSION\u CODES.M){
如果(ContextCompat.checkSelfPermission)(此,
清单.权限.访问(位置)
==PackageManager.权限(已授予){
buildGoogleAppClient();
mGoogleMap.setMyLocationEnabled(true);
}否则{
checkLocationPermission();
}
}否则{
buildGoogleAppClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
受保护的同步无效BuildGoogleAppClient(){
mgoogleapclient=新的Googleapclient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@凌驾
公共无效onRequestPermissionsResult(int requestCode,
字符串权限[],int[]grantResults){
开关(请求代码){
案例我的权限请求
 new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            // This method will be executed once the timer is over
            // insert your data to db here


            // close this activity
            finish();
        }
    }, TIME_OUT);
private static int TIME_OUT = 10000;
public class LocationBackGroundService extends Service implements LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "LocationBackGroundService";
    private static final long INTERVAL = 100;
    private static final long FASTEST_INTERVAL = 100;

    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mCurrentLocation;
    Context mCOntext;

    public void LocationBackGroundService(Context mContext) {
        this.mCOntext = mContext;
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        mGoogleApiClient.connect();
    }

    @Override
    public void onCreate() {
        super.onCreate();

        if (!isGooglePlayServicesAvailable()) {
            // finish();
        }
        createLocationRequest();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
        }
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            return false;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onConnected(Bundle bundle) {
        startLocationUpdates();
    }


    protected void startLocationUpdates() {
        PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

        Log.d(TAG, "Location update started ..............: ");
    }

    @Override
    public void onConnectionSuspended(int i) {

        Toast.makeText(this, "OnConnection Suspended", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this, "OnConnection Failed", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLocationChanged(Location location) {

        if (null != mCurrentLocation) {
            mCurrentLocation = location;
            String lat = String.valueOf(mCurrentLocation.getLatitude());
            String lng = String.valueOf(mCurrentLocation.getLongitude());

        }
    }
}
startService(new Intent(this, yourBackgroundServiceName.class));
<service android:name=".yourBackgroundServiceName"></service>