How can I get continuous location updates in Android like in Google Maps?

前端 未结 4 762
猫巷女王i
猫巷女王i 2020-12-02 11:26

I\'m building a friend tracking android app. While my friend activated the app and goes away along with his GPS and cellular data on, I need to track him on my device. That\

4条回答
  •  一整个雨季
    2020-12-02 12:12

    I believe rather than reinventing the wheel, you can use one of the third party libraries that are easy to implement and in this case, battery efficient. One of the library I found is SmartLocation. You can add the following dependency in your build.gradle (app) to start using the library.

    compile 'io.nlopez.smartlocation:library:3.2.9'
    

    After adding the dependency, you should rebuild the project to get the references.

    As an example you can try the following code in your Activity.

    Button start_btn=(Button)findViewById(R.id.start_location_streaming);
    
    Context context = start_btn.getContext();
    
    Handler handler = new Handler();
    
    start_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SmartLocation.with(context).location().start(locationListener);
        }
    });
    
    OnLocationUpdatedListener locationListener = new OnLocationUpdatedListener({
        @Override
        public void onLocationUpdated(Location location) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            handler.postDelayed(locationRunnable,8000);
        }
    });
    
    Runnable locationRunnable = new Runnable({
        @Override
        public void run() {
            SmartLocation.with(context).location().start(locationListener);
        }
    });
    

    You can stop location tracking in onStop() method

    @Override
    public void onStop() {
        SmartLocation.with(context).location().stop();
        super.onStop();
    }
    

    SmartLocation library will give you more than what is expected, just try that once.

    Note: Make sure your application does have ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION (both) to have accurate results. Don't forget to ask for permissions at runtime for Android 6.0 and above.

提交回复
热议问题