繁体   English   中英

无法在Android设备上检测到用户当前位置

[英]Unable to detect user current location on android device

我正在开发要在其中查找用户当前位置的小型android应用程序。 我用于检测用户位置的代码结构如下所示。

private void sendSMS(Context context, Intent intent)
{ 
     final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
     final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

     LocationManager locationManager;
     locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 

     locationManager.requestLocationUpdates(
         LocationManager.GPS_PROVIDER, 
     MINIMUM_TIME_BETWEEN_UPDATES, 
     MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
    new MyLocationListener()
     );

     Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
     String loc_message = null;

     if (location != null) 
     {
     loc_message =String.format(
         "Current Location \n Longitude: %1$s \n Latitude: %2$s",
         location.getLongitude(), location.getLatitude()
      );
    Toast.makeText(context, loc_message,Toast.LENGTH_LONG).show();
     }
}   
 private class MyLocationListener implements LocationListener {

         public void onLocationChanged(Location location) {
         String message = String.format(
                 "New Location \n Longitude: %1$s \n Latitude: %2$s",
                 location.getLongitude(), location.getLatitude()
         );
     }

     public void onStatusChanged(String s, int i, Bundle b) {

     }

     public void onProviderDisabled(String s) {
     }

     public void onProviderEnabled(String s) {
     }
     }
}

我可以从DDMS发送坐标的模拟器上正常工作。 但是,当我在设备上运行它时,却没有输出任何信息。在我的设备上,我保持启用``使用GPS卫星''功能。 但是,当我尝试查找用户位置时,它没有给出任何输出。...需要帮助...谢谢.......

这是我在跟踪应用程序中使用的GPS Service的框架,它已经过测试,并且可以保证正常运行。 希望对您有所帮助。

import java.util.Timer;
import java.util.TimerTask;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceManager;
import android.util.Log;

public class TrackingService extends Service {
    private static final String TAG = TrackingService.class.getSimpleName();

    private static final long TIME_BETWEEN_UPDATES = 1000L;
    private static final long MINIMUM_DISTANCE_CHANGE = 0L;

    private WakeLock mWakeLock;

    private LocationManager mLocationManager;

    private final Timer mTimer = new Timer();
    private Handler mHandler = new Handler();

    private LocationListener mLocationListenerGps = new LocationListener() {

        public void onLocationChanged(Location location) {
            // Your code here
        }

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

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
        }
    };

    private void registerLocationListener() {
        if (mLocationManager == null) {
            Log.e(TAG, "TrackingService: Do not have any location manager.");
            return;
        }
        Log.d(TAG, "Preparing to register location listener w/ TrackingService...");
        try {
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE, mLocationListenerGps);
            Log.d(TAG, "...location listener now registered w/ TrackingService @ " + TIME_BETWEEN_UPDATES);
        } catch (RuntimeException e) {
            Log.e(TAG, "Could not register location listener: " + e.getMessage(), e);
        }
    }

    private void unregisterLocationListener() {
        if (mLocationManager == null) {
            Log.e(TAG, "TrackingService: Do not have any location manager.");
            return;
        }
        mLocationManager.removeUpdates(mLocationListenerGps);
        Log.d(TAG, "Location listener now unregistered w/ TrackingService.");
    }

    private TimerTask mCheckLocationListenerTask = new TimerTask() {
        @Override
        public void run() {
            mHandler.post(new Runnable() {
                public void run() {
                    Log.d(TAG, "Re-registering location listener with TrackingService.");
                    unregisterLocationListener();
                    registerLocationListener();
                }
            });
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();

        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        registerLocationListener();

        mTimer.schedule(mCheckLocationListenerTask, 1000 * 60 * 5, 1000 * 60);

        acquireWakeLock();

        Log.d(TAG, "Service started...");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        handleStartCommand(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handleStartCommand(intent, startId);
        return START_STICKY;
    }

    private void handleStartCommand(Intent intent, int startId) {
        Notification notification = new Notification(R.drawable.ic_launcher,
                getText(R.string.trackingservice_notification_rolling_text),
                System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class),
                PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(this,
                getText(R.string.trackingservice_notification_ticker_title),
                getText(R.string.trackingservice_notification_ticker_text),
                contentIntent);

        startForeground(1, notification);
    }

    @Override
    public void onDestroy() {
        stopForeground(true);
        mTimer.cancel();
        mTimer.purge();
        mHandler.removeCallbacksAndMessages(null);
        unregisterLocationListener();
        releaseWakeLock();
        super.onDestroy();
        Log.d(TAG, "Service stopped...");
    }

    private void acquireWakeLock() {
        try {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            if (pm == null) {
                Log.e(TAG, "TrackRecordingService: Power manager not found!");
                return;
            }
            if (mWakeLock == null) {
                mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
                if (mWakeLock == null) {
                    Log.e(TAG, "TrackRecordingService: Could not create wake lock (null).");
                    return;
                }
            }
            if (!mWakeLock.isHeld()) {
                mWakeLock.acquire();
                if (!mWakeLock.isHeld()) {
                    Log.e(TAG, "TrackRecordingService: Could not acquire wake lock.");
                }
            }
        } catch (RuntimeException e) {
            Log.e(TAG, "TrackRecordingService: Caught unexpected exception: "
                    + e.getMessage(), e);
        }
    }

    /**
     * Releases the wake lock if it's currently held.
     */
    private void releaseWakeLock() {
        if (mWakeLock != null && mWakeLock.isHeld()) {
            mWakeLock.release();
            mWakeLock = null;
        }
    }
}

并且在您的AndroidManifest.xml文件中,您需要

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

只需填写GPS位置侦听器,在AndroidManifest.xml注册该服务,然后从您的活动中启动该服务即可享受。

Nilkash,我在三星Galaxy 5上遇到了同样的问题。

由于您建议更改为网络提供商,我的问题得到了解决。 谢谢你的好友。 我找到了解决方案。

“网络提供商”根据基站和WiFi接入点的可用性确定位置。 通过网络查找来检索结果。 需要权限android.permission.ACCESS_COARSE_LOCATION或android.permission.ACCESS_FINE_LOCATION。

但是“ GPS提供商”使用卫星来确定位置。 根据条件,此提供程序可能需要一段时间才能返回位置信息。 需要权限android.permission.ACCESS_FINE_LOCATION。

这是设备的问题,没有互联网,我们的设备不支持GPS,它仅使用位置提供程序。

暂无
暂无

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

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