2017-05-08 116 views
2

我正在使用NET_PROVIDER檢查當前的經度和緯度,並將它們打印爲應用程序中的toast消息。 然而,經許可設置和連接的網絡,經度和緯度始終返回0.0安卓經緯度返回0.0

我做了什麼固定的:

  1. 設置權限
  2. onLocationChanged方法保存先前的位置
  3. 我試着在模擬器和真實設備(api22)。但都返回0給我。

enter image description here

這裏是我的代碼。

TrackGps.java

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.os.Bundle; 
import android.os.IBinder; 
import android.provider.Settings; 


import android.support.v4.app.ActivityCompat; 
import android.util.Log; 
import android.widget.Toast; 

/** 
* Created by Hannah Liao on 5/7/2017 
*/ 

public class TrackGps extends Service implements LocationListener { 

    private final Context mContext; 

    boolean checkNetwork = false; 

    boolean canGetLocation = false; 
    LocationListener locationListener; 
    Location loc ; 
    double latitude; 
    double longitude; 


    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; 


    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; 
    protected LocationManager locationManager; 

    public TrackGps(Context mContext) { 
     this.mContext = mContext; 
     getLocation(); 
    } 

    private Location getLocation() { 

     try { 
      locationManager = (LocationManager) mContext 
        .getSystemService(LOCATION_SERVICE); 

      checkNetwork = locationManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if(!checkNetwork) { 
       Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show(); 
      } else { 
       this.canGetLocation = true; 
       // First get location from Network Provider 
       if (checkNetwork) { 
        Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show(); 

        try { 
         locationManager.requestLocationUpdates(
           LocationManager.NETWORK_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
         Log.d("Network", "Network"); 

         if (locationManager != null) { 
          loc = locationManager 
            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
          this.onLocationChanged(loc); 
         } 

         if (loc != null) { 
          latitude = loc.getLatitude(); 
          longitude = loc.getLongitude(); 
         } 
        } catch (SecurityException e) { 

        } 
       } 
      } 
      // if GPS Enabled get lat/long using GPS Services 
      // otherwise just use network 
      /*if (checkGPS) { 
       Toast.makeText(mContext, "GPS", Toast.LENGTH_SHORT).show(); 
       if (loc == null) { 
        try { 
         locationManager.requestLocationUpdates(
           LocationManager.GPS_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener); 
         Log.d("GPS Enabled", "GPS Enabled"); 
         if (locationManager != null) { 
          loc = locationManager 
            .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          if (loc != null) { 
           latitude = loc.getLatitude(); 
           longitude = loc.getLongitude(); 
          } 
         } 
        } catch (SecurityException e) { 

        } 
       } 
      }*/ 

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

     return loc; 
    } 

    public double getLongitude() { 
     if (loc != null) { 
      longitude = loc.getLongitude(); 
     } 
     return longitude; 
    } 

    public double getLatitude() { 
     if (loc != null) { 
      latitude = loc.getLatitude(); 
     } 
     return latitude; 
    } 

    public boolean canGetLocation() { 
     return this.canGetLocation; 
    } 

    public void showSettingsAlert() { 
     AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 


     alertDialog.setTitle("GPS Not Enabled"); 

     alertDialog.setMessage("Do you wants to turn On GPS"); 


     alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       mContext.startActivity(intent); 
      } 
     }); 


     alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.cancel(); 
      } 
     }); 


     alertDialog.show(); 
    } 



    public void stopUsingGPS() { 
     if (locationManager != null) { 

      locationManager.removeUpdates(TrackGps.this); 
     } 
    } 

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

    @Override 
    public void onLocationChanged(Location location) { 
      this.loc = location; 
      getLocation(); 
      getLongitude(); 
      getLatitude(); 
    } 

    @Override 
    public void onStatusChanged(String s, int i, Bundle bundle) { 

    } 

    @Override 
    public void onProviderEnabled(String s) { 

    } 

    @Override 
    public void onProviderDisabled(String s) { 

    } 

MainActivity.java

import android.content.Intent; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.Toast; 

public class MainActivity extends AppCompatActivity { 

    private Button b_get; 
    private TrackGps gps; 
    double longitude; 
    double latitude; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     b_get = (Button)findViewById(R.id.get); 
     b_get.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 

       gps = new TrackGps(MainActivity.this); 

       if(gps.canGetLocation()){ 


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

         Toast.makeText(getApplicationContext(),"Longitude:"+String.valueOf(longitude)+"\nLatitude:"+Double.toString(latitude),Toast.LENGTH_SHORT).show(); 
       } 
       else 
       { 

        gps.showSettingsAlert(); 
       } 

      } 
     }); 
    } 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     gps.stopUsingGPS(); 
    } 
} 

清單

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.map.hannah.location3"> 

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> 
    <uses-permission android:name="android.permission.INTERNET"/> 
    <uses-feature android:name="android.hardware.location.gps" /> 
    <application 


     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:roundIcon="@mipmap/ic_launcher_round" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 

     <activity android:name=".MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 
       <service android:name=".TrackGps" android:enabled="true" /> 
       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 

gradle這個

apply plugin: 'com.android.application' 

android { 
    compileSdkVersion 25 
    buildToolsVersion "25.0.3" 
    defaultConfig { 
     applicationId "com.map.hannah.location3" 
     minSdkVersion 17 
     targetSdkVersion 25 
     versionCode 1 
     versionName "1.0" 
     testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 
    } 
    buildTypes { 
     release { 
      minifyEnabled false 
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
     } 
    } 
} 

dependencies { 
    compile fileTree(dir: 'libs', include: ['*.jar']) 
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 
     exclude group: 'com.android.support', module: 'support-annotations' 
    }) 
    compile 'com.android.support:appcompat-v7:25.3.1' 
    compile 'com.android.support.constraint:constraint-layout:1.0.2' 
    testCompile 'junit:junit:4.12' 
} 
+0

https://stackoverflow.com/q/43082062/115145 – CommonsWare

+0

讀什麼@CommonsWare共享的'getLastKnownLocation' – njzk2

+0

的文檔似乎非常有用,也許這個問題適合作爲重複。另外,當沒有數據可用時,不是0.0的默認位置? – Alfabravo

回答

0
For Api marshmallow and above use run time permission as: 
if (ContextCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_FINE_LOCATION) 
     == PackageManager.PERMISSION_GRANTED) { 
// do your work 
} else { 
// request permission. 
     ActivityCompat.requestPermissions(this, new String[] 
{ 
Manifest.permission.ACCESS_FINE_LOCATION}, MY_LOCATION_REQUEST_CODE); 
} 

public void onRequestPermissionsResult(int requestCode, String[] 
permissions, int[] grantResults) { 
if (requestCode == MY_LOCATION_REQUEST_CODE) { 
if (permissions.length == 1 && 
    permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION && 
    grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
/// granted do your work 
} else { 
    // Permission was denied. Display an error message. 
    } 
}