2016-11-16 48 views
1

我有一個LocationManager,應該讓我從Android設備上的按鈕點擊GPS經緯度。我的問題是,它總是給我0.0我不明白這是什麼問題。我在MyLocation.java和AndroidManifest.xml中給了它權限,我也檢查了是否有gps信號。Android LocationManager給出了0.0的經度和緯度

MyLocation.java

public class MyLocation 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 MyLocation(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; 
      if (isNetworkEnabled) { 
       if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
         || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("Network", "Network"); 
       } 
       if (locationManager != null) { 
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
          || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        } 
        if (location != null) { 
         if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
           || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
          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){ 
     if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
       || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
      locationManager.removeUpdates(MyLocation.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 is 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 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; 
} 

} 

tablelayout.java

public class tablelayout extends Activity implements View.OnClickListener { 
Button btn, btn2; 
MyLocation myLocation; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.bundle2); 
      /* create button */ 
    btn=(Button)findViewById(R.id.Button01); 
    btn.setOnClickListener(this); 
      /* delete button */ 
    btn2=(Button)findViewById(R.id.Button02); 
    btn2.setOnClickListener(this); 
} 

public void onClick(View view){ 
    if (view == btn) { 
     TableLayout tl = (TableLayout) findViewById(R.id.TableLayout01); 
     TableRow tr = new TableRow(this); 

      /* get date */ 
     SimpleDateFormat dtformat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); 
     Date mydate = new Date(); 
     String dateString = dtformat.format(mydate); 
     TextView dt = new TextView(this); 
     dt.setText(dateString); 
     dt.setGravity(Gravity.CENTER_HORIZONTAL); 

      /* get time */ 
     SimpleDateFormat tmformat = new SimpleDateFormat("HH:mm", Locale.getDefault()); 
     Date mytime = new Date(); 
     String timeString = tmformat.format(mytime); 
     TextView tm = new TextView(this); 
     tm.setText(timeString); 
     tm.setGravity(Gravity.CENTER_HORIZONTAL); 

      /* drop-down list */ 

     String[] species = getResources().getStringArray(R.array.speciesList); 
     ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,species); 
     AutoCompleteTextView autoComplete = new AutoCompleteTextView(this); 
     autoComplete.setAdapter(adapter); 
     autoComplete.setThreshold(1); 
     autoComplete.setDropDownWidth(ViewGroup.LayoutParams.MATCH_PARENT); 
     autoComplete.setTextSize(10); 
     int options = autoComplete.getImeOptions(); 
     autoComplete.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_ACTION_DONE|EditorInfo.IME_FLAG_NO_FULLSCREEN); 

      /* GPS location */ 

     TextView latitudeTv = new TextView(this); 
     TextView longitudeTv = new TextView(this); 

     // create class object 
     myLocation = new MyLocation(tablelayout.this); 

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

      Double latitude =myLocation.getLatitude(); 
      Double longitude =myLocation.getLongitude(); 

      latitudeTv.setText(latitude.toString()); 
      longitudeTv.setText(longitude.toString()); 
     } else { 
      // can't get location 
      // GPS or Network is not enabled 
      // Ask user to enable GPS/network in settings 
      myLocation.showSettingsAlert(); 
     } 

      /* user input */ 
     EditText et3 = new EditText(this); 
     et3.setImeOptions(options|EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_ACTION_DONE); 
     et3.setInputType(InputType.TYPE_CLASS_NUMBER); 
     EditText et4 = new EditText(this); 
     et4.setImeOptions(options|EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_ACTION_DONE); 

     tr.addView(dt); 
     tr.addView(tm); 
     tr.addView(autoComplete); 
     tr.addView(latitudeTv); 
     tr.addView(longitudeTv); 
     tr.addView(et3); 
     tr.addView(et4); 
     tl.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT)); 
    } 
    if (view == btn2) { 
     TableLayout tl = (TableLayout) findViewById(R.id.TableLayout01); 
     int rowNumber = tl.getChildCount(); 
     tl.removeViews(rowNumber-1,1); 
    } 
    } 

} 

AndroidManifest.java

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

請參閱http://stackoverflow.com/a/23823363/6616489。似乎已經使用'location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);'之前使用location.getLatitude()/ .getLongitude(); –

+0

getLastKnownLocation()常規返回null。樂觀地使用它,但要準備採取額外的步驟(例如,調用requestLocationUpdates())來獲取位置數據。這涵蓋在任何體面的Android書籍或涵蓋'LocationManager'的培訓課程中。 – CommonsWare

回答

0

這問題與懶惰的GPS傳感器和延遲有關。所以你有2個解決方案的基礎上您的需求

1-啓動和實例你的onLocklistener(例如在oncreate)myLocation類。所以當你點擊你的按鈕時,你的手機傳感器會有一段時間與衛星同步。

2-在您的活動之外(在它之前)和myLocation onLocationChanged方法中啓動myLocation,將位置參數發送到另一個類中的靜態var(例如:sharingGps)。所以你可以從每個活動和類別共享你的位置