Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

android - How to update longitude and latitude in every 10 seconds in mysql database?

I'm trying to get latitude and longitude from Android device and send it to MySQL database. when any one register his current latitude and longitude saved in the database.but i want to know that how to update saved latitude and longitude in every 10 seconds.here is my code:

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 - 
Lat: " + getlatitude + "
Long: " + 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("");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to use threads for this purpose , with time out of 10 seconds so every 10 seconds your code in thread will run

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

And set time out as

private static int TIME_OUT = 10000;

Here you go :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...