0

我是 Android 新手,正在开发一个应用程序,其中我的小部件显示 Location latlong。我正在通过配置活动执行此操作。在刷新按钮上刷新相同的位置。一切正常,但小部件上的活动屏幕闪烁。我希望从服务中获得相同的输出,以便活动屏幕不会在前面闪烁。

为此,我创建了一项服务,该服务在单击刷新按钮时启动,但现在我如何在使用地图视图、位置管理器等服务时进行编码,而这些服务不允许。

4

1 回答 1

0

在您的服务中,您可以使用以下内容:

    private void startPositionListener() {
        if (mLocationManager == null) {
            // Get the location manager
            mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        }
        try {
            gpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            networkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception e) {
            Log.e(TAG, e.getLocalizedMessage());
        }
        // Register the listener with the Location Manager to receive location updates
        if(gpsEnabled) {
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 1, mGpsListener);
            Log.d(TAG, "GPS Listener started.");
        } else if(networkEnabled) { // Checking for GSM
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 6000, 1, mNetworkListener);
            Log.d(TAG, "Network Listener started.");
        }
}

WheremNetworkListenermGpsListenerare 实现LocationListener. 您必须填写的唯一方法是onLocationChanged(Location)(这是您在服务中获取位置数据的地方)。完成以下操作后不要忘记停止更新这些对象:

private void stopPositionListner() {
        if (mLocationManager != null) {
            mLocationManager.removeUpdates(mGpsListener);
            mLocationManager.removeUpdates(mNetworkListener);
            Log.d(TAG, "Position Listener stopped.");
        }
    }
于 2012-08-03T08:19:38.950 回答