使用GPS时启动Android应用程序

时间:2013-11-21 05:50:27

标签: android gps

我希望在任何应用程序使用GPS时自动启动我的服务,并在不再使用GPS时停止服务。如果可能的话,我想避免让我的服务在后台运行。

显然,“GPS已激活”没有广播意图,例如“启动已完成”。那将是完美的开始我的服务。我的另一个想法是在LocationManager注册一个GpsStatus.Listener,但我认为我的应用程序必须一直在后台运行(并且需要自动启动权限)。

我想这样做的原因是我想在使用时收集GPS状态信息。

感谢您的想法!

1 个答案:

答案 0 :(得分:0)

你可以这样做

 @Override 
    public void onCreate(Bundle savedInstanceSate){
                super.onCreate(savedInstaceState);
                setContentView(R.layout.main);
                //Location methods
                locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                locationListener = new GpsLocationListener();
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    }
    class GpsLocationListener implements LocationListener {
            @Override
            public void onLocationChanged(Location location) {
            **write  here methods for services when your GPS is active or working**
                Toast.makeText(context, "Location Data Updated", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onProviderDisabled(String provider) {
                Toast.makeText(context, "Gps Disabled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onProviderEnabled(String provider) {
                Toast.makeText(context, "Gps Enabled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

        }