我正在根据gmaps和地理位置开发一个小应用程序。
这是calcolate long和lat获得我的位置的方法:
public List<Object> getLocation(Activity act) {
List<Object> parameters = new ArrayList();
//controllo se il GPS è attivo
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//verifico lo stato della connessione
isNetworkrEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnable && !isNetworkrEnable) {
return null;
} else {
if (isNetworkrEnable) {
if (ActivityCompat.checkSelfPermission(act, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(act, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return null;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
Log.d("NETWORK CHECK", "NETWORK ATTIVO!");
if(locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null){
latitudine = location.getLatitude();
longitudine = location.getLongitude();
parameters.add(location);
parameters.add(latitudine);
parameters.add(longitudine);
}
}
}
if(isGPSEnable){
if(isGPSEnable){
if(location == null){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Log.d("GPS CHECK", "GPS ATTIVO!");
if(locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
latitudine = location.getLatitude();
longitudine = location.getLongitude();
parameters.add(location);
parameters.add(latitudine);
parameters.add(longitudine);
}
}
}
}
}
}
return parameters;
}
&#13;
这是我的清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="francescoperfetti.mamba.it.futureselfdrive_gmaps">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<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" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity
android:name=".MainMapsActivity"
android:label="@string/title_activity_main_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
&#13;
位置始终为null,我在模拟器上检查了什么或者问题是什么?
谢谢你,祝你有个美好的一天。
弗朗西斯。
答案 0 :(得分:0)
以下是我的代码,它返回用户当前位置:
以下是服务类:
package com.anonymous.attendancemange.servicess;
import android.Manifest;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.anonymous.attendancemange.util.Util;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
/**
* Created by bitcode on 24/8/15.
*/
//GoogleApiClient.ConnectionCallbacks ,GoogleApiClient.OnConnectionFailedListener,LocationListener
public class MyService extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient googleApiClient;
private LocationRequest mLocationRequest;
private static String TAG = "test";
private GetLocationRef mGetLocationRef;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
buildGoogleApiClient();
createLocationRequest();
}
@Override
public synchronized void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
if (googleApiClient != null)
stopLocationUpdates();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStart");
if (googleApiClient != null) {
googleApiClient.connect();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onLocationChanged(Location location) {
Log.d("test", "location changes main .");
if (location != null) {
Util.currntLocation = location;
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "State Changed.");
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(30000);
mLocationRequest.setFastestInterval(30000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void startLocationUpdates() {
Log.d(TAG, "StartLocationUpdates");
mGetLocationRef = new GetLocationRef();
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck == android.content.pm.PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, mGetLocationRef);
}
}
protected void stopLocationUpdates() {
Log.d(TAG, "StopUpdate");
if (mGetLocationRef != null)
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, mGetLocationRef);
}
@Override
public void onConnected(Bundle bundle) {
Log.d("test", "connected");
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck == android.content.pm.PackageManager.PERMISSION_GRANTED) {
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (mLastLocation != null) {
Util.currntLocation = mLastLocation;
}
if (googleApiClient != null)
startLocationUpdates();
}
}
@Override
public void onConnectionSuspended(int i) {
}
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "failed.....");
}
public class GetLocationRef implements com.google.android.gms.location.LocationListener {
@Override
public void onLocationChanged(Location location) {
// Log.d("test","location changes.");
if (location != null) {
Util.currntLocation = location;
}
}
}
}
这是Util calss,我存储当前位置:
package com.anonymous.attendancemange.util;
import android.location.Location;
/**
* Created by sos on 1/10/2016.
*/
public class Util {
public static Location currntLocation;
}
只需在主要活动中添加以下行即可开始服务:
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
Folloing是主要文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.anonymous.attendancemange" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.anonymous.attendancemange.SplashScreenActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.anonymous.attendancemange.ActivityLogin"
android:screenOrientation="portrait"
></activity>
<activity android:name="com.anonymous.attendancemange.MainActivity"
android:screenOrientation="portrait"
></activity>
<activity android:name=".ActivityOfficessCheckin"
android:screenOrientation="portrait"
></activity>
<service android:name=".servicess.MyService"></service>
</application>
</manifest>
您想要使用当前位置的位置:
if(Util.currntLocation!=null){
Log.d("test", "lat:" + Util.currntLocation.getLatitude() + "Long:" + Util.currntLocation.getLongitude());
}