Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/219.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
com.google.android.gms.location.LocationListener';s位置已更改,未调用_Android - Fatal编程技术网

com.google.android.gms.location.LocationListener';s位置已更改,未调用

com.google.android.gms.location.LocationListener';s位置已更改,未调用,android,Android,我正在创建一个请求locationUpdate的服务。但是 LocationChanged回调仅在未调用服务之后首次启动时调用。Location changed应在2km changed上调用。我是否做错了什么 package com.example.qwerty; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api

我正在创建一个请求locationUpdate的服务。但是 LocationChanged回调仅在未调用服务之后首次启动时调用。Location changed应在2km changed上调用。我是否做错了什么

       package com.example.qwerty;
     import com.google.android.gms.common.ConnectionResult;

        import com.google.android.gms.common.api.GoogleApiClient;

        import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;

        import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;

        import com.google.android.gms.location.LocationRequest;

        import com.google.android.gms.location.LocationServices;

        import com.google.android.gms.location.LocationListener;




        import android.os.IBinder;


        //Location Callback
        public class LocationService extends Service  implements ConnectionCallbacks,OnConnectionFailedListener  {

         private class locationListener  implements LocationListener   {

            public void addLocation(String loc){
                SharedPreferences pref= getSharedPreferences(Contant.MYPREFERENCE, MODE_PRIVATE);
                Editor edit = pref.edit();  
                String s ="";
                if(pref.contains("location")){
                      s =    pref.getString("location", "");
                     } 
                     s  = s + loc;
                     edit.putString("location",s).commit();
                    }

        public void getAddress( final double latitude , final double longitude){
                new AsyncTask<Double, Void, String>() {
                    @Override
                    protected String doInBackground(Double...params){ 
                        Geocoder geocoder = new Geocoder(LocationService.this,Locale.getDefault());
                        String result ="";
                        List<Address> addressList =null;
                        try {
                            addressList = geocoder.getFromLocation(
                                    params[0], params[1], 1);
                         if (addressList != null && addressList.size() > 0) {
                            Address address = addressList.get(0);
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                                sb.append(address.getAddressLine(i)).append("\n");
                            }
                            sb.append(address.getLocality()).append("\n");
                            sb.append(address.getPostalCode()).append("\n");
                            sb.append(address.getCountryName());
                            result = sb.toString();
                        }
                    }
                        catch (Exception e) {
                              result =e.toString(); 
                              result  = result + " " +  latitude +  "  "+  longitude;
                        } 

                        return result;
                    }
                        @Override
                        protected void onPostExecute(String result) {   
                           addLocation(result); 
                        }
                  }.execute(latitude , longitude);
        } 
         @Override
            public void onLocationChanged(Location location) {

                if(NetworkState.isNetConnected(LocationService.this)) {
                    getAddress(location.getLatitude(), location.getLongitude());                                                        
                }else{
                    addLocation(" lat " +  location.getLatitude()+ "  long " + location.getLongitude());
                } 
            }

            }


         GoogleApiClient client  =  null;
                public LocationService() {

                }

            @Override   
            public int onStartCommand(Intent intent, int flags, int startId) {
                SharedPreferences pref= getSharedPreferences(Contant.MYPREFERENCE, MODE_PRIVATE);
                client = new GoogleApiClient.Builder(this)
                 .addApi(LocationServices.API)
                 .addConnectionCallbacks(this)
                 .addOnConnectionFailedListener(this)
                 .build();  
                 client.connect();


               return START_STICKY;


            }
              @Override
                public void onDestroy() {


             }

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

            @Override
            public void onConnected(Bundle arg0) {
                LocationRequest mLocationRequest = new LocationRequest();
                mLocationRequest.setInterval(420000);
                mLocationRequest.setSmallestDisplacement(1000);

                LocationServices.FusedLocationApi.requestLocationUpdates(client, mLocationRequest , new locationListener());

            }

            @Override
            public void onConnectionSuspended(int arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onConnectionFailed(ConnectionResult arg0) {


            }
        }
package com.example.qwerty;
导入com.google.android.gms.common.ConnectionResult;
导入com.google.android.gms.common.api.GoogleAppClient;
导入com.google.android.gms.common.api.GoogleAppClient.ConnectionCallbacks;
导入com.google.android.gms.common.api.GoogleAppClient.OnConnectionFailedListener;
导入com.google.android.gms.location.LocationRequest;
导入com.google.android.gms.location.LocationServices;
导入com.google.android.gms.location.LocationListener;
导入android.os.IBinder;
//位置回调
公共类LocationService扩展服务实现ConnectionCallbacks、OnConnectionFailedListener{
私有类locationListener实现locationListener{
公共无效添加位置(字符串位置){
SharedReferences pref=GetSharedReferences(Contant.MYPREFERENCE,MODE_PRIVATE);
编辑器编辑=pref.edit();
字符串s=“”;
if(pref.contains(“位置”)){
s=pref.getString(“位置”,“位置”);
} 
s=s+loc;
edit.putString(“location”,s).commit();
}
公共地址(最终双纬度、最终双经度){
新建异步任务(){
@凌驾
受保护字符串doInBackground(双…参数){
Geocoder Geocoder=新的地理编码器(LocationService.this,Locale.getDefault());
字符串结果=”;
List addressList=null;
试一试{
addressList=geocoder.getFromLocation(
参数[0],参数[1],1);
if(addressList!=null&&addressList.size()>0){
地址=地址列表。获取(0);
StringBuilder sb=新的StringBuilder();
对于(int i=0;i
anyother而不是that。anyother而不是that。
In my app,I integrated this service class for getting location datas(Latitude,longitude).Make changes where ever is required.Give it a try.
You can directly call getLatitude() and getLongitude() methods in other activities to get the lat,long value.Implement the method calling as per your requirement.hope it might help you.

     public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS settings");
        alertDialog.setCancelable(false);

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location)
    {

    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

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

}
I got another solution that work for me.may be it helps other in near future.
1)Set up alaram for n minutes

2)On this alaram  set a  broadcast.When you receive broadcast start a service which will get the current location.

3)After getting location stop that service.

4)The same thing goes on and on.