2017-02-12 69 views
0

我想在android studio中創建一個原始的「獲取當前位置的應用程序」。爲什麼我的android應用程序總是給經度和緯度0?

一旦我按下主頁面上的按鈕,我希望當前的經度和緯度顯示在烤麪包上。出於某種原因,它們一直顯示爲0.0。

我一直在經歷調試器,我發現網絡提供商不可用。我不知道這是否是由於在android studio上使用模擬器。

如果有人能告訴我問題是什麼/如何解決這將是驚人的。

這是我的MainActivity

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.Toast; 

public class MainActivity extends Activity { 

Button btnShowLocation; 

// GPSTracker class 
GPSTracker gps; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    btnShowLocation = (Button) findViewById(R.id.show_location); 

    // show location button click event 
    btnShowLocation.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      // create class object 
      gps = new GPSTracker(MainActivity.this); 

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

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

       // \n is for new line 
       Toast.makeText(getApplicationContext(), "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(); 
      } 

     } 
    }); 
} 

} 

這裏是我的GPSTracker類

import android.Manifest; 
import android.app.AlertDialog; 
import android.app.Service; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.pm.PackageManager; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.provider.Settings; 
import android.support.v4.app.ActivityCompat; 
import android.util.Log; 
import android.widget.Toast; 


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; 

boolean canGetLocation = false; 

Location location; 
double latitude; 
double longitude; 

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

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

//Declaring location manager 
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 available 
     } else { 
      this.canGetLocation = true; 

      //First get location from provider 
      if (isGPSEnabled) { 


       if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
         != PackageManager.PERMISSION_GRANTED && 
         ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) 
         != PackageManager.PERMISSION_GRANTED) { 
        showSettingsAlert(); 
       } 
       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.GPS_PROVIDER); 
        Toast.makeText(this, location.toString(), Toast.LENGTH_SHORT).show(); 
        if (location != null) { 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
        } 
       } 

      } 
     } 

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

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

/** 
* 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 if best network provider 
* @return boolean 
* */ 
public boolean canGetLocation() { 
    return this.canGetLocation; 
} 

/** 
* Function to show settings alert dialog 
* */ 
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?"); 

    // Setting Icon to Dialog 

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

/** 
* Stop using GPS listener 
* Calling this function will stop using GPS in your app 
* */ 
public void stopUsingGPS() { 
    if (locationManager != null) { 
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      showSettingsAlert(); 
     } 
     locationManager.removeUpdates(GPSTracker.this); 
    } 
} 



} 

而且我androidManifest如果需要

<?xml version="1.0" encoding="utf-8"?> 

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme"> 
    <activity android:name=".MainActivity"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
<uses-permission android:name="android.permission.INTERNET" /> 

+0

而非isProviderEnabled(),有你試用getBestProvider()? – Shine

+0

我試過了。我真的不知道如何使用這個功能,所以它沒有太多幫助。 – gtgaito

+0

是的。另外,我認爲網絡提供商需要COARSE位置訪問。在任何情況下,如果您已經計劃了ACCESS_FINE – Shine

回答

0

包括許可<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>,然後再嘗試這樣的:

@Override 
public void onRequestPermissionsResult(int requestCode, @NonNull 
     String permissions[], @NonNull int[] grantResults) { 
    switch (requestCode) { 

     case Constants.MY_PERMISSIONS_ACCESS_COARSE_LOCATION: { 
      // If request is cancelled, the result arrays are empty. 
      if (grantResults.length > 0 
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
       provider = locationManager.getBestProvider(SoulissUtils.getGeoCriteria(), true); 
       Log.w(TAG, "MY_PERMISSIONS_ACCESS_COARSE_LOCATION permission granted"); 

       if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED 
         && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
        Log.wtf(TAG, "user changed mind?"); 
        return; 
       } 
       locationManager.requestLocationUpdates(provider, Constants.POSITION_UPDATE_INTERVAL, 
         Constants.POSITION_UPDATE_MIN_DIST, this); 
       Location location = locationManager.getLastKnownLocation(provider); 
       // Initialize the location fields 
       if (location != null) { 
        onLocationChanged(location); 
       } 

      } else { 
       // USER denial, log something 
      } 
      return; 
     } 

     // other 'case' lines to check for other 
     // permissions the app might request 
    } 
} 

然後移動下面的代碼:

  if (locationManager != null) { 
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
        Toast.makeText(this, location.toString(), Toast.LENGTH_SHORT).show(); 
        if (location != null) { 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
        } 
       } 

到覆蓋onLocationChanged()方法

+0

我應該在哪裏放置onRequestPermissionResult()? – gtgaito

+0

在我的服務中,我想。這個想法是:請求權限,當/如果授予(onRequestPermissionResult()),初始化bestProvider並請求位置更新。然後,在onLocationChanged()中,完成這項工作 – Shine

+0

Constraints根本就不是我編譯的 – gtgaito

相關問題