2014-01-30 5 views
0

탭 레이아웃에서 3 조각 클래스가 있고 그 중 하나에서 현재 위치 (위도 & 경도)를 가져 오는 버튼을 구현했습니다. 모든 위도와 경도를 나타내는 값을 제외하고 잘 작동 0왜 위도와 경도가 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 클래스

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

    } 

답변

0

당신의 조건에 경우에, 나는 think.if GPS는 다음 네트워크에서 위치를 가져올 수있게되지 않는 문제가 있습니다 공급자 및 네트워크 제공 업체의 옵션 -> (무선 네트워크 사용)이 위치 서비스 설정에서 사용 가능해야하며 인터넷 연결이 작동해야합니다. 기본 작동의 경우 링크를 찾으십시오. enter link description here

0

AndroidManifest.xml 파일에 추가 했습니까?

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

ACCESS_COURSE_LOCATION 대신에 ACCESS_CO (A) RSE_LOCATION –

0

android studio에서 모니터 컨트롤을 사용하여 좌표를 변경할 수 있습니다. Tools-> Android-> Android Device Monitor로 이동해야합니다. 그것은 윈도우를 보여줍니다,이 에뮬레이터 컨트롤을 선택하십시오 하단에 좌표 (경도, 고도)를 변경할 수 있습니다

+0

거기 에뮬레이터 경도와 고도를 보낼 수 있습니다 –

관련 문제