Android手机启动后获取GPS位置,我试图在服务中获取它,但位置返回为null

时间:2011-07-05 11:09:26

标签: android service gps location boot

这是代码。

我怎么能确定,该位置是alwasys而不是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){}
     }
} 

1 个答案:

答案 0 :(得分:0)

我建议创建一个回叫界面,并使用onLocationChanged通知该位置首次启动时回拨。

LocationProvider locationProvider = LocationManager.NETWORK_PROVIDER;
// Or use LocationManager.GPS_PROVIDER

Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

我希望这对你有所帮助。