开发者

Android get GPS Location after phone boots, I am trying to get it in a service but location returned as null

开发者 https://www.devze.com 2023-03-17 21:41 出处:网络
Here is the code. How can I be sure, that location is returned alwasys instead of null. package com.test.location;

Here is the code.

How can I be sure, that location is returned alwasys instead of 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 on开发者_开发技巧ProviderEnabled(String provider){}
         public void onStatusChanged(String provider, int status, Bundle extras){}
     }
} 


I recommend to create a call back interface and use onLocationChanged which notifies that call back on the moment the location initiate for the first time.

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

Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
0

精彩评论

暂无评论...
验证码 换一张
取 消