質問

I have 3 fragment class in tab layout and in one of them I have implemented a button to get the current location(latitude & longitude). Everything works fine except the latitude and longitude showing value 0.

    package com.swipetab.example;

        import java.util.Calendar;

        import android.app.DatePickerDialog.OnDateSetListener;
        import android.app.TimePickerDialog.OnTimeSetListener;
        import android.content.Context;
        import android.os.Bundle;
        import android.support.v4.app.DialogFragment;
        import android.support.v4.app.Fragment;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.view.View.OnClickListener;
        import android.widget.Button;
        import android.widget.TextView;
        import android.widget.TimePicker;
        import android.widget.Toast;

        public class FragmentC extends Fragment {
            Button Date, Time, GpsBtn;
            GPSTracker gps;

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
                View myFragmentView = inflater.inflate(R.layout.fragment_c, container,
                        false);
                Date = (Button) myFragmentView.findViewById(R.id.button1);
                Time = (Button) myFragmentView.findViewById(R.id.button2);
                GpsBtn = (Button) myFragmentView.findViewById(R.id.button3);
                Date.setOnClickListener(DateOnClickListener);
                Time.setOnClickListener(TimeOnClickListener);
                GpsBtn.setOnClickListener(GPSOnClickListener);

                return myFragmentView;
            }

            OnClickListener DateOnClickListener = new OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    showDatePicker();

                }
            };

            OnClickListener TimeOnClickListener = new OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    showTimePicker();

                }
            };
            OnClickListener GPSOnClickListener = new OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    showGPSLocation();

                }
            };

            private void showDatePicker() {
                DatePicker date = new DatePicker();
                /**
                 * Set Up Current Date Into dialog
                 */
                Calendar calender = Calendar.getInstance();
                Bundle args = new Bundle();
                args.putInt("year", calender.get(Calendar.YEAR));
                args.putInt("month", calender.get(Calendar.MONTH));
                args.putInt("day", calender.get(Calendar.DAY_OF_MONTH));
                date.setArguments(args);
                /**
                 * Set Call back to capture selected date
                 */
                date.setCallBack(ondate);

                date.show(getFragmentManager(), "Date Picker");
            }

            private void showTimePicker() {
                Time time = new Time();
                /**
                 * Set Up Current Time Into dialog
                 */
                Calendar calender = Calendar.getInstance();
                Bundle args = new Bundle();
                args.putInt("hour", calender.get(Calendar.HOUR_OF_DAY));
                args.putInt("min", calender.get(Calendar.MINUTE));
                time.setArguments(args);
                /**
                 * Set Call back to capture selected date
                 */
                time.setCallBack(ontime);

                time.show(getFragmentManager(), "Time Picker");
            }

            private void showGPSLocation() {
                gps = new GPSTracker(getActivity());

                // check if GPS enabled
                if (gps.canGetLocation()) {

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    // \n is for new line
                    Toast.makeText(
                            getActivity(),
                            "Your Location is - \nLat: " + latitude + "\nLong: "
                                    + longitude, Toast.LENGTH_LONG).show();
                } else {
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();

                }
            }

            OnDateSetListener ondate = new OnDateSetListener() {

                @Override
                public void onDateSet(android.widget.DatePicker arg0, int year,
                        int month, int day) {
                    // TODO Auto-generated method stub

                    String TabOfFragmentB = ((MainActivity) getActivity())
                            .getTabFragmentB();

                    FragmentB fragmentB = (FragmentB) getActivity()
                            .getSupportFragmentManager().findFragmentByTag(
                                    TabOfFragmentB);

                    String y = Integer.toString(year);
                    String m = Integer.toString(month);
                    String d = Integer.toString(day);

                    String dat = y.concat("-") + m.concat("-") + d;

                    fragmentB.b_updateDate(dat);

                    Toast.makeText(
                            getActivity(),
                            String.valueOf(year) + "-" + String.valueOf(month) + "-"
                                    + String.valueOf(day), Toast.LENGTH_LONG).show();
                }
            };
            OnTimeSetListener ontime = new OnTimeSetListener() {

                @Override
                public void onTimeSet(TimePicker arg0, int hourOfDay, int min) {
                    // TODO Auto-generated method stub
                    String TabOfFragmentB = ((MainActivity) getActivity())
                            .getTabFragmentB();

                    FragmentB fragmentB = (FragmentB) getActivity()
                            .getSupportFragmentManager().findFragmentByTag(
                                    TabOfFragmentB);
                    int hour;
                    String am_pm;
                    if (hourOfDay > 12) {
                        hour = hourOfDay - 12;
                        am_pm = "PM";
                    } else {
                        hour = hourOfDay;
                        am_pm = "AM";
                    }
                    String h = Integer.toString(hour);
                    String m = Integer.toString(min);

                    String t = h.concat(":") + m + " " + am_pm;

                    fragmentB.b_updateTime(t);

                    Toast.makeText(getActivity(),
                            String.valueOf(hour) + "-" + String.valueOf(min),
                            Toast.LENGTH_LONG).show();
                }
            };
        }

GPSTracker class

    package com.swipetab.example;

    import android.app.AlertDialog;
    import android.app.Service;
    import android.content.Context;
    import android.content.DialogInterface;
    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.provider.Settings;
    import android.util.Log;

    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();
        }

        private Location getLocation() {
            // TODO Auto-generated method stub
            try {
                locationManager = (LocationManager) mContext
                        .getSystemService(LOCATION_SERVICE);
                // getting GPS status
                isGPSEnabled = locationManager
                        .isProviderEnabled(LocationManager.GPS_PROVIDER);
                if (!isGPSEnabled && !isNetworkEnabled) {
                    // no network provider is enabled
                    System.out.println("Please Enable!!");
                } else {
                    this.canGetLocation = true;
                    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");

            // 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 arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderDisabled(String arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public IBinder onBind(Intent arg0) {
            // TODO Auto-generated method stub
            return null;
        }

    }
役に立ちましたか?

解決

your if conditions, are the problems i think.if GPS is not enable then you fetch the location from network provider and for network provider your option ->(use wireless network )should be enable in location service settings and your internet connection should be working.and for basic working please find the link.enter link description here

他のヒント

Have you added this to your AndroidManifest.xml file?

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION"/>

You can change the coordinates using the monitor control in android studio. You must go to Tools->Android->Android Device Monitor. It show a windows, in this windows, you choose Emulator Control, in the bottom you can change the coordinates (longitude, altitude)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top