【问题标题】:Current Location Background service is not working当前位置后台服务不工作
【发布时间】:2016-03-23 09:23:42
【问题描述】:

我需要从我的服务类中获取当前位置并将最近获取的值传递给活动类。但是使用这个类我无法获取当前位置的纬度和经度。这是我的代码。请检查一下。

服务类:

public class MyLocation extends Service {
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled = false;
    boolean network_enabled = false;
    Context con;
    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            if (ActivityCompat.checkSelfPermission(con, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(con, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    };
    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            if (ActivityCompat.checkSelfPermission(con, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(con, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

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

    public boolean getLocation(Context context, LocationResult result) {
        con = context;
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult = result;
        if (lm == null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try {
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }
        try {
            network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }

        //don't start listeners if no provider is enabled
        if (!gps_enabled && !network_enabled)
            return false;

        if (gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        if (network_enabled)
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return network_enabled;
            }
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
        timer1 = new Timer();
        timer1.schedule(new GetLastLocation(), 20000);
        return true;
    }

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

    public static abstract class LocationResult {
        public abstract void gotLocation(Location location);
    }

    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
            lm.removeUpdates(locationListenerGps);
            if (ActivityCompat.checkSelfPermission(con, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(con, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            lm.removeUpdates(locationListenerNetwork);

            Location net_loc = null, gps_loc = null;
            if (gps_enabled)
                gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (network_enabled)
                net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            //if there are both values use the latest one
            if (gps_loc != null && net_loc != null) {
                if (gps_loc.getTime() > net_loc.getTime())
                    locationResult.gotLocation(gps_loc);
                else
                    locationResult.gotLocation(net_loc);
                return;
            }

            if (gps_loc != null) {
                locationResult.gotLocation(gps_loc);
                return;
            }
            if (net_loc != null) {
                locationResult.gotLocation(net_loc);
                return;
            }
            locationResult.gotLocation(null);
        }
    }
}

【问题讨论】:

  • 实际问题是什么? onLocationChanged 根本没有被调用?或者它被调用并且你不能将结果传递给活动?或者是其他东西?此外,考虑使用 Google Play Services API 来提供位置服务 - 建议 Android 开发者网站使用。
  • onLocationChanged 未被调用。
  • lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork); - 如果启用了网络提供商,您甚至不在这里检查。你检查它上面的视图线,但你对结果没有做任何事情。另外,如果您没有权限,我认为不会调用 onLocationChanged - 因此检查 onLocationChanged 内部的权限是没有意义的(不过我可能错了)。
  • 在 GPS_PROVIDER 的情况下,您将获得位置或 onLocationChanged 将仅在您移动时调用。

标签: android service gps location


【解决方案1】:

请尝试使用此 GPSTracker.java 获取当前位置 lat lng

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;
    boolean isGPSEnabled = false;// flag for GPS status
    boolean isNetworkEnabled = false;// flag for network status
    boolean canGetLocation = false;// flag for GPS status
    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    /* How many GeoCoder should return our GPSTracker */
    int geocoderMaxResults = 1;

    /* 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 */
                //gpsEnableAlertDialog();
            } 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,LNG 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
     * application
     * */
    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;
    }

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

        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
     * launch Settings Options
     * */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        /* Setting Dialog Title */
        //alertDialog.setTitle("GPS is settings");

        /* Setting Dialog Message */
        alertDialog.setMessage("GPS is disabled in your device. Enable it?");

        /* On pressing Settings button */
        alertDialog.setPositiveButton("Enable GPS", 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();
    }


    /*
     * Close project which is open 
     * this sialog is used to disable all menu item
     */
    private void gpsEnableAlertDialog() {

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_close_project, null);

        final NiftyDialogBuilder dialogBuilder = NiftyDialogBuilder.getInstance(mContext);
        dialogBuilder.isCancelableOnTouchOutside(true).withDuration(700).withEffect(Effectstype.Shake).setCustomView(view,mContext).show();

        TextView edt_searchitem_item = (TextView) view.findViewById(R.id.edt_searchitem_item);
        edt_searchitem_item.setText("GPS is disabled in your device. Enable it?");
        /*
         * Close project and disable all menu item
         */
        Button btn_closePrj_yes = (Button) view.findViewById(R.id.btn_closePrj_yes);
        btn_closePrj_yes.setText("Enable GPS");
        btn_closePrj_yes.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialogBuilder.cancel();
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
                ((Activity)mContext).overridePendingTransition(R.anim.right_to_left_layout,R.anim.left_to_right_layout);
            }
        });


        /*
         * return same as previouse state
         */
        Button btn_close_prj_no = (Button) view.findViewById(R.id.btn_close_prj_no);
        btn_close_prj_no.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialogBuilder.cancel();
            }
        });
    }

    @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;
    }

    /* Extra(Below method not use in application) */

    /**
     * Get list of address by latitude and longitude
     * 
     * @return null or List<Address>
     */
    public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {

            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);

            try {
                /**
                 * Geocoder.getFromLocation - Returns an array of Addresses that
                 * are known to describe the area immediately surrounding the
                 * given latitude and longitude.
                 */
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);

                return addresses;
            } catch (IOException e) {
                Toast.makeText(context, "Internet connection not available", Toast.LENGTH_SHORT).show();
                Log.e("Error Msg:", "Impossible to connect to Geocoder", e);
            }
        }

        return null;
    }

    /**
     * Try to get AddressLine
     * 
     * @return null or addressLine
     */
    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);

            return addressLine;
        } else {
            return null;
        }
    }

    /**
     * Try to get Locality
     * 
     * @return null or locality
     */
    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();

            return locality;
        } else {
            return null;
        }
    }

    /**
     * Try to get Postal Code
     * 
     * @return null or postalCode
     */
    public String getPostalCode(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String postalCode = address.getPostalCode();

            return postalCode;
        } else {
            return null;
        }
    }

    /**
     * Try to get CountryName
     * 
     * @return null or postalCode
     */
    public String getCountryName(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String countryName = address.getCountryName();

            return countryName;
        } else {
            return null;
        }
    }
}

【讨论】:

    【解决方案2】:

    从这里下载项目 (Get Current Location Using Background Service)

    activity_main.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:background="#ffffff"
        android:layout_height="match_parent">
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="#3F51B5"
            android:text="Location using service"
            android:textColor="#ffffff"
            android:textSize="20dp"
            android:gravity="center"/>
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
    
            android:orientation="vertical">
    
    
    
        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="horizontal"
            android:layout_height="50dp">
    
            <TextView
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:text="Latitude"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp"
                android:textColor="#000000"
                android:textSize="20dp"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:id="@+id/tv_latitude"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp"
                android:textColor="#000000"
                android:textSize="20dp"/>
    
    
        </LinearLayout>
    
            <LinearLayout
                android:layout_width="match_parent"
                android:orientation="horizontal"
                android:layout_height="50dp">
    
                <TextView
                    android:layout_width="150dp"
                    android:layout_height="wrap_content"
                    android:text="Longitude"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="10dp"
                    android:textColor="#000000"
                    android:textSize="20dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=""
                    android:id="@+id/tv_longitude"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="10dp"
                    android:textColor="#000000"
                    android:textSize="20dp"/>
    
    
            </LinearLayout>
    
            <LinearLayout
                android:layout_width="match_parent"
                android:orientation="horizontal"
                android:layout_height="50dp">
    
                <TextView
                    android:layout_width="150dp"
                    android:layout_height="wrap_content"
                    android:text="Address"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="10dp"
                    android:textColor="#000000"
                    android:textSize="20dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=""
                    android:id="@+id/tv_address"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="10dp"
                    android:textColor="#000000"
                    android:textSize="20dp"/>
    
    
            </LinearLayout>
    
            <LinearLayout
                android:layout_width="match_parent"
                android:orientation="horizontal"
                android:layout_height="50dp">
    
                <TextView
                    android:layout_width="150dp"
                    android:layout_height="wrap_content"
                    android:text="Area"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="10dp"
                    android:textColor="#000000"
                    android:textSize="20dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=""
                    android:id="@+id/tv_area"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="10dp"
                    android:textColor="#000000"
                    android:textSize="20dp"/>
    
    
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:orientation="horizontal"
                android:layout_height="50dp">
    
                <TextView
                    android:layout_width="150dp"
                    android:layout_height="wrap_content"
                    android:text="Locality"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="10dp"
                    android:textColor="#000000"
                    android:textSize="20dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=""
                    android:id="@+id/tv_locality"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="10dp"
                    android:textColor="#000000"
                    android:textSize="20dp"/>
    
    
            </LinearLayout>
    
        </LinearLayout>
    
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/btn_start"
            android:text="Get Location"
            android:layout_alignParentBottom="true"/>
    
    
    
    </RelativeLayout>
    

    MainActivity.java

    import android.*;
    import android.app.Activity;
    import android.app.ActivityManager;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.content.SharedPreferences;
    import android.content.pm.PackageManager;
    import android.location.Address;
    import android.location.Geocoder;
    import android.preference.PreferenceManager;
    import android.renderscript.Double2;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import java.io.IOException;
    import java.util.List;
    import java.util.Locale;
    
    public class MainActivity extends Activity {
        Button btn_start;
        private static final int REQUEST_PERMISSIONS = 100;
        boolean boolean_permission;
        TextView tv_latitude, tv_longitude, tv_address,tv_area,tv_locality;
        SharedPreferences mPref;
        SharedPreferences.Editor medit;
        Double latitude,longitude;
        Geocoder geocoder;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            btn_start = (Button) findViewById(R.id.btn_start);
            tv_address = (TextView) findViewById(R.id.tv_address);
            tv_latitude = (TextView) findViewById(R.id.tv_latitude);
            tv_longitude = (TextView) findViewById(R.id.tv_longitude);
            tv_area = (TextView)findViewById(R.id.tv_area);
            tv_locality = (TextView)findViewById(R.id.tv_locality);
            geocoder = new Geocoder(this, Locale.getDefault());
            mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            medit = mPref.edit();
    
    
            btn_start.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (boolean_permission) {
    
                        if (mPref.getString("service", "").matches("")) {
                            medit.putString("service", "service").commit();
    
                            Intent intent = new Intent(getApplicationContext(), GoogleService.class);
                            startService(intent);
    
                        } else {
                            Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show();
                    }
    
                }
            });
    
            fn_permission();
        }
    
        private void fn_permission() {
            if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
    
                if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {
    
    
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION
    
                            },
                            REQUEST_PERMISSIONS);
    
                }
            } else {
                boolean_permission = true;
            }
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    
            switch (requestCode) {
                case REQUEST_PERMISSIONS: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        boolean_permission = true;
    
                    } else {
                        Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
    
                    }
                }
            }
        }
    
        private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
    
                latitude = Double.valueOf(intent.getStringExtra("latutide"));
                longitude = Double.valueOf(intent.getStringExtra("longitude"));
    
                List<Address> addresses = null;
    
                try {
                    addresses = geocoder.getFromLocation(latitude, longitude, 1);
                    String cityName = addresses.get(0).getAddressLine(0);
                    String stateName = addresses.get(0).getAddressLine(1);
                    String countryName = addresses.get(0).getAddressLine(2);
    
                    tv_area.setText(addresses.get(0).getAdminArea());
                    tv_locality.setText(stateName);
                    tv_address.setText(countryName);
    
    
    
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
    
    
                tv_latitude.setText(latitude+"");
                tv_longitude.setText(longitude+"");
                tv_address.getText();
    
    
            }
        };
    
        @Override
        protected void onResume() {
            super.onResume();
            registerReceiver(broadcastReceiver, new IntentFilter(GoogleService.str_receiver));
    
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            unregisterReceiver(broadcastReceiver);
        }
    
    
    }
    

    GoogleService.java

    package servicetutorial.service;
    
    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.Handler;
    import android.os.IBinder;
    import android.support.annotation.Nullable;
    import android.util.Log;
    
    import java.util.Timer;
    import java.util.TimerTask;
    
    /**
     * Created by deepshikha on 24/11/16.
     */
    
    public class GoogleService extends Service implements LocationListener{
    
        boolean isGPSEnable = false;
        boolean isNetworkEnable = false;
        double latitude,longitude;
        LocationManager locationManager;
        Location location;
        private Handler mHandler = new Handler();
        private Timer mTimer = null;
        long notify_interval = 1000;
        public static String str_receiver = "servicetutorial.service.receiver";
        Intent intent;
    
    
    
    
        public GoogleService() {
    
        }
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            mTimer = new Timer();
            mTimer.schedule(new TimerTaskToGetLocation(),5,notify_interval);
            intent = new Intent(str_receiver);
    //        fn_getlocation();
        }
    
        @Override
        public void onLocationChanged(Location location) {
    
        }
    
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
    
        }
    
        @Override
        public void onProviderEnabled(String provider) {
    
        }
    
        @Override
        public void onProviderDisabled(String provider) {
    
        }
    
        private void fn_getlocation(){
            locationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
            isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    
            if (!isGPSEnable && !isNetworkEnable){
    
            }else {
    
                if (isNetworkEnable){
                    location = null;
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000,0,this);
                    if (locationManager!=null){
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location!=null){
    
                            Log.e("latitude",location.getLatitude()+"");
                            Log.e("longitude",location.getLongitude()+"");
    
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            fn_update(location);
                        }
                    }
    
                }
    
    
                if (isGPSEnable){
                    location = null;
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
                    if (locationManager!=null){
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location!=null){
                            Log.e("latitude",location.getLatitude()+"");
                            Log.e("longitude",location.getLongitude()+"");
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            fn_update(location);
                        }
                    }
                }
    
    
            }
    
        }
    
        private class TimerTaskToGetLocation extends TimerTask{
            @Override
            public void run() {
    
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        fn_getlocation();
                    }
                });
    
            }
        }
    
        private void fn_update(Location location){
    
            intent.putExtra("latutide",location.getLatitude()+"");
            intent.putExtra("longitude",location.getLongitude()+"");
            sendBroadcast(intent);
        }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      相关资源
      最近更新 更多