简体   繁体   English

使用后台服务定期获取位置,保存在Android中的本地数据库中

[英]Get Location Periodically Using Background Services,Save In Local Database in Android

1.In My application ,I want to track User Current Location Every 1 minute then Save in Local Database. 1.在我的应用程序中,我想每1分钟跟踪一次用户当前位置,然后保存到本地数据库中。 Not getting Proper location Some times ,when user is Walking . 找不到正确的位置有时,当用户正在行走时

2.For finding location ,I want to use Google play Services API. 2.要查找位置,我想使用Google Play服务API。

My Need: 我的需求:

Background Service Should get the location, save in local Database every minute.Even Application is Closed. 后台服务应该获取位置,每分钟保存在本地数据库中。即使应用程序已关闭。

also with low Battery Usage . 电池使用率

I tried Some codes some methods are deprecated and not Working. 我尝试了某些代码,但某些方法已弃用,无法正常工作。

Please Suggest me any solution. 请建议我任何解决方案。

This is one of the way you can achieve it, make your service class like below 这是实现它的一种方法,使服务类如下

here, 这里,

with this ScheduledThreadPoolExecutor your service will be on in background and you will need LocationManager 使用此ScheduledThreadPoolExecutor,您的服务将在后台运行,并且您将需要LocationManager

your SERVICE.class extend Service implements LocationListener, Runnable 您的SERVICE.class扩展服务实现了LocationListener,Runnable

    private LocationManager mgr = null;
    private ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);



        @Override
         public void onCreate() {
                 //check gps is on/off
                 //get locationmanager
          }

         @Override
         public int onStartCommand(Intent intent, int flags, int startId) {
                  //check if internet is on/off
                  setBeforeDelay15();
                  return super.onStartCommand(intent, flags, startId);
         }

         @Override
         public void onLocationChanged(Location location) {
                   //re-execute at time you need with **scheduleAtFixedRate**
         }

         @Override
         public void run() {
                 //here get the best location from two ways 1>gps and 2>network provider
                 //once you get this insert to database
                 //set delay then request call method  again
         }

          @Override
          public void onDestroy() {
                //if locationmanager is not null then remove all updates
          }

         private void setDelay15() {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {             
                    // Log.e("srop self by", "delay15");   
                    startWork();           
                }
            }, 300000);//120000
        }

private void startWork() {
//check here for 1>gps and 2>network provider
//get location and save it
}

use this , when you require location in your application. 当您需要在应用程序中定位时,请使用this。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM