正确地在后台获取位置更新?

时间:2015-12-26 11:21:43

标签: android location

我在我的应用中实现了位置服务,最近我更新了它以获取后台位置更新。但是,我不确定这是否是“正确的方式”。我正在使用网络位置提供程序并调用onStart以尽快获取位置更新(0,0)。当用户最小化应用程序(应用程序进入后台并且调用onPause)时,我不太频繁地请求更新 - 每30分钟,每200米。我想知道我的逻辑是否正确,我的应用程序将在后台获得这些更新。我有两个类变量来存储经度和纬度值。

这是我的mainActvity代码:

public class MainActivity extends AppCompatActivity {
public double latitude = 0.0;
public double longitude = 0.0;
private MyLocationListener locationListner;
private LocationManager locationManager;
public boolean isFirstTimeLaunchingTheApp = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //-----------MY CODE STARTS HERE-----------------
    mainActivityLayout = (LinearLayout)findViewById(R.id.main_activity_layout);
    changeWindowTopColor();
    this.mCurrent_forecast_fragment = new Current_forecast_fragment();
    this.mHourly_forecast_fragment = new Hourly_forecast_fragment();
    this.mDaily_forecast_fragment = new Daily_forecast_fragment();
    locationListner = new MyLocationListener();

    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
    adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs, mCurrent_forecast_fragment,
            mHourly_forecast_fragment, mDaily_forecast_fragment);

    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);
    pager.setOffscreenPageLimit(3);
    pager.setAdapter(adapter);

    // Assiging the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

    // Setting Custom Color for the Scroll bar indicator of the Tab View
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return ContextCompat.getColor(MainActivity.this, R.color.tabsScrollColor);
        }
    });

    // Setting the ViewPager For the SlidingTabsLayout
    tabs.setViewPager(pager);

}

@Override
protected void onResume() {
    super.onResume();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        if (locationManager == null) {
            getLocation();
            Log.d(TAG, "OnResume locationManager == null");
        }
}

@Override
protected void onStart() {
    super.onStart();
    getLocation();
    Log.d(TAG, "onStart getLocation");
}

@Override
protected void onPause() {
    super.onPause();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    locationManager.removeUpdates(locationListner);
        //EVERY HALF AN HOUR
        long minTime = 30 * 60 * 1000;
        //EVERY 200 meters
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minTime , 200 , locationListner);
    Log.d(TAG, "requestLocationUpdates in the BACKGROUND...");
}

@Override
protected void onDestroy() {
    if(locationManager != null) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.removeUpdates(locationListner);
        Log.d(TAG,"removeUpdates - onDestroy");
    }
    super.onDestroy();
    Log.d(TAG, "onDestroy called");
}
public void getLocation() {
    if(!isFirstTimeLaunchingTheApp && isNetworkAvailable()){
        final Snackbar snackbar = Snackbar
                .make(mainActivityLayout, "Initial launch may take a bit more to load.", Snackbar.LENGTH_LONG)
                .setAction("OK", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    }
                });

        snackbar.show();
    }
    Log.d(TAG,"getLocation initiated...");
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    if (isNetworkAvailable()) {
//            mCurrent_forecast_fragment.toggleRefresh();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        //check if the if the location services are enabled
        if( !isLocationServicesEnabled()) {
            alertForNoLocationEnabled();
        }else {
            Log.d(TAG,"getLocation  requestLocationUpdates...");
            locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 0, 0, locationListner);
        }

    } else {
        alertForNoInternet();
        Log.d(TAG, "Alert No Internet" + 366);
    }
}
 private class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location loc) {
        Log.d(TAG,"On Location changed...");
        latitude = loc.getLatitude();
        longitude = loc.getLongitude();
        //check if this is the first time that the app starts
        //if it is not, get the forecast only with the swiperefresh layout
        if(!isFirstTimeLaunchingTheApp) {
            getForecast(latitude, longitude);
            isFirstTimeLaunchingTheApp = true;
        }
    }

1 个答案:

答案 0 :(得分:0)

每当您的位置发生变化时,

requestlocationUpdate()都会调用侦听器的onLocationChanged()方法,并且它也会在后台执行。

您可以使用AsyncTaskService解决此问题。

使用Service

public class loc extends Service
{
    LocationManager loc_manager;

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub

        loc_manager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        loc_manager.requestLocationUpdates("gps",0,0,listener);

        return super.onStartCommand(intent, flags, startId);
    }

    LocationListener listener=new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub  
        }
    };
}

别忘了在Manifest文件中注册您的服务和位置权限。