【问题标题】:Android get GPS Location after phone boots, I am trying to get it in a service but location returned as nullAndroid 在手机启动后获取 GPS 位置,我试图在服务中获取它,但位置返回为 null
【发布时间】:2011-07-05 11:09:25
【问题描述】:

这里是代码。

我如何确定该位置始终返回而不是 null。

package com.test.location;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
 public class NotifyOnBoot extends Service  {
        Location location;

        @Override
        public IBinder onBind(Intent arg0) {
         return null;
        }

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

                     updateNotification();

                     Thread th = new Thread(null, task, "myService");
                     th.start();
         }

        private Runnable task = new Runnable() {
         public void run() {

            if(location == null)
            {
                Log.d("location","No location");
            }
            else
                Log.d("location",location.toString());


            NotifyOnBoot.this.stopSelf();
         }
     };

     @Override
     public void onDestroy() {
         super.onDestroy();
     }

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


     protected void updateNotification()
     {
         LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
         LocationListener locationListener = new MyLocationlistener();
         lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
         location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
     }
     private class MyLocationlistener implements LocationListener{
         public void onLocationChanged(Location location){}
         public void onProviderDisabled(String provider){}
         public void onProviderEnabled(String provider){}
         public void onStatusChanged(String provider, int status, Bundle extras){}
     }
} 

【问题讨论】:

    标签: android service gps location boot


    【解决方案1】:

    我建议创建一个回调接口并使用onLocationChanged,它会在位置首次启动时通知回调。

    LocationProvider locationProvider = LocationManager.NETWORK_PROVIDER;
    // Or use LocationManager.GPS_PROVIDER
    
    Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
    

    【讨论】:

    • 你能具体一点吗:)
    • 创建一个处理程序并将其用作回调。因此,当调用处理程序时,只需使用 lat long 坐标。
    • 嗨,rohit,当我在模拟器中更改位置时,我能够获取位置,但我想要的总是在手机启动时获取位置(当前或最后已知)
    猜你喜欢
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 2017-04-16
    • 2013-08-05
    • 2011-07-19
    • 1970-01-01
    • 2016-09-30
    • 2012-02-08
    相关资源
    最近更新 更多