Turn GPS on programmatically like Ola Cabs Android app

前端 未结 7 877
忘了有多久
忘了有多久 2021-02-04 15:44

I am working on an application and need to integrate GPS location. I want to switch the GPS on programmatically. The condition is: I don\'t want to send the user to the Setting

7条回答
  •  醉话见心
    2021-02-04 16:21

    I've created a library based on Anirudh answer.

    Short guide how to use it:

    1. Add it to you build.gradle file:

      compile 'net.alexandroid.utils:gps:1.6'

    2. Implement GpsStatusDetectorCallBack interface.

    3. Implement interface methods: onGpsSettingStatus and onGpsAlertCanceledByUser

    4. Create instance variable:

      private GpsStatusDetector mGpsStatusDetector;
      
    5. Instantiate it in onCreate():

       mGpsStatusDetector = new GpsStatusDetector(this);
      
    6. In place you need to check the status and show a dialog if need add:

      mGpsStatusDetector.checkGpsStatus();
      
    7. Override onActivityResult and add there:

      mGpsStatusDetector.checkOnActivityResult(requestCode, resultCode);
      

    More information about the library: https://github.com/Pulimet/GpsDetector-Library


    Example:

    public class MainActivity extends AppCompatActivity implements GpsStatusDetector.GpsStatusDetectorCallBack {
    
        private GpsStatusDetector mGpsStatusDetector;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mGpsStatusDetector = new GpsStatusDetector(this);
            mGpsStatusDetector.checkLocationSettingStatus();
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            mGpsStatusDetector.checkOnActivityResult(requestCode, resultCode);
        }
    
        @Override
        public void onGpsSettingStatus(boolean enabled) {
            Log.d("TAG", "onGpsSettingStatus: " + enabled);
        }
    
        @Override
        public void onGpsAlertCanceledByUser() {
            Log.d("TAG", "onGpsAlertCanceledByUser");
        }
    }
    

提交回复
热议问题