在我的Android应用程序,我想得到用户的当前位置每隔几分钟间隔和更新到我的中心服务器使用网络服务。目前我正在使用融合位置提供获取用户当前位置,请参阅链接
现在我想知道频繁获取用户位置和调用web服务的最佳方法是什么。
下面是我的代码,它为我提供了用户当前位置:-
locationrequest = LocationRequest.create();
locationrequest.setInterval(10000);
locationclient.requestLocationUpdates(locationrequest,new com.google.android.gms.location.LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.i(TAG, "Last Known Location :" + location.getLatitude() + "," + location.getLongitude());
}
});
现在从这里我必须调用这个代码。我可以在后台服务或其他地方使用它吗。
请提供你的想法。
蒂亚。
开启服务后ACCESS_FINE_LOCATIONACCESS_COARSE_LOCATION授予所需权限
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.location.LocationListener;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import java.util.concurrent.TimeUnit;
/**
* Created by Ketan Ramani on 05/11/18.
*/
public class BackgroundLocationUpdateService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
/* Declare in manifest
<service android:name=".BackgroundLocationUpdateService"/>
*/
private final String TAG = "BackgroundLocationUpdateService";
private final String TAG_LOCATION = "TAG_LOCATION";
private Context context;
private boolean stopService = false;
/* For Google Fused API */
protected GoogleApiClient mGoogleApiClient;
protected LocationSettingsRequest mLocationSettingsRequest;
private String latitude = "0.0", longitude = "0.0";
private FusedLocationProviderClient mFusedLocationClient;
private SettingsClient mSettingsClient;
private LocationCallback mLocationCallback;
private LocationRequest mLocationRequest;
private Location mCurrentLocation;
/* For Google Fused API */
@Override
public void onCreate() {
super.onCreate();
context = this;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
StartForeground();
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
try {
if (!stopService) {
//Perform your task here
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (!stopService) {
handler.postDelayed(this, TimeUnit.SECONDS.toMillis(10));
}
}
}
};
handler.postDelayed(runnable, 2000);
buildGoogleApiClient();
return START_STICKY;
}
@Override
public void onDestroy() {
Log.e(TAG, "Service Stopped");
stopService = true;
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
Log.e(TAG_LOCATION, "Location Update Callback Removed");
}
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void StartForeground() {
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
String CHANNEL_ID = "channel_location";
String CHANNEL_NAME = "channel_location";
NotificationCompat.Builder builder = null;
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager.createNotificationChannel(channel);
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
builder.setChannelId(CHANNEL_ID);
builder.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE);
} else {
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
}
builder.setContentTitle("Your title");
builder.setContentText("You are now online");
Uri notificationSound = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(notificationSound);
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_logo);
builder.setContentIntent(pendingIntent);
Notification notification = builder.build();
startForeground(101, notification);
}
@Override
public void onLocationChanged(Location location) {
Log.e(TAG_LOCATION, "Location Changed Latitude : " + location.getLatitude() + "\tLongitude : " + location.getLongitude());
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLongitude());
if (latitude.equalsIgnoreCase("0.0") && longitude.equalsIgnoreCase("0.0")) {
requestLocationUpdate();
} else {
Log.e(TAG_LOCATION, "Latitude : " + location.getLatitude() + "\tLongitude : " + location.getLongitude());
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onConnected(@Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
mLocationSettingsRequest = builder.build();
mSettingsClient
.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.e(TAG_LOCATION, "GPS Success");
requestLocationUpdate();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
int REQUEST_CHECK_SETTINGS = 214;
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult((AppCompatActivity) context, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sie) {
Log.e(TAG_LOCATION, "Unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.e(TAG_LOCATION, "Location settings are inadequate, and cannot be fixed here. Fix in Settings.");
}
}
}).addOnCanceledListener(new OnCanceledListener() {
@Override
public void onCanceled() {
Log.e(TAG_LOCATION, "checkLocationSettings -> onCanceled");
}
});
}
@Override
public void onConnectionSuspended(int i) {
connectGoogleClient();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
mSettingsClient = LocationServices.getSettingsClient(context);
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
connectGoogleClient();
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
Log.e(TAG_LOCATION, "Location Received");
mCurrentLocation = locationResult.getLastLocation();
onLocationChanged(mCurrentLocation);
}
};
}
private void connectGoogleClient() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int resultCode = googleAPI.isGooglePlayServicesAvailable(context);
if (resultCode == ConnectionResult.SUCCESS) {
mGoogleApiClient.connect();
}
}
@SuppressLint("MissingPermission")
private void requestLocationUpdate() {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
}
活跃
启动服务:startService(新的意图(这个,BackgroundLocationUpdateService.class))
停止服务:
stopService(新意图(this,BackgroundLocationUpdateService.class))
零碎
启动服务:
getActivity()。startService(新意图(getActivity()。getBaseContext(),BackgroundLocationUpdateService。类),
停止服务:
getActivity()。stopService(新意图(getActivity(),BackgroundLocationUpdateService)。类),
从这里下载源代码(使用后台服务获取当前位置)
AndroidManifest。xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="servicetutorial.service">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<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"
android:theme="@android:style/Theme.Translucent.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".GoogleService"></service>
</application>
</manifest>
主要活动。xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#ffffff"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#3F51B5"
android:text="Location using service"
android:textColor="#ffffff"
android:textSize="20dp"
android:gravity="center"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="50dp">
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Latitude"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="@+id/tv_latitude"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="50dp">
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Longitude"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="@+id/tv_longitude"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="50dp">
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Address"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="@+id/tv_address"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="50dp">
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Area"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="@+id/tv_area"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="50dp">
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Locality"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="@+id/tv_locality"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:textColor="#000000"
android:textSize="20dp"/>
</LinearLayout>
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn_start"
android:text="Get Location"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
主要活动。JAVA
package servicetutorial.service;
import android.*;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.preference.PreferenceManager;
import android.renderscript.Double2;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends Activity {
Button btn_start;
private static final int REQUEST_PERMISSIONS = 100;
boolean boolean_permission;
TextView tv_latitude, tv_longitude, tv_address,tv_area,tv_locality;
SharedPreferences mPref;
SharedPreferences.Editor medit;
Double latitude,longitude;
Geocoder geocoder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.btn_start);
tv_address = (TextView) findViewById(R.id.tv_address);
tv_latitude = (TextView) findViewById(R.id.tv_latitude);
tv_longitude = (TextView) findViewById(R.id.tv_longitude);
tv_area = (TextView)findViewById(R.id.tv_area);
tv_locality = (TextView)findViewById(R.id.tv_locality);
geocoder = new Geocoder(this, Locale.getDefault());
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
medit = mPref.edit();
btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (boolean_permission) {
if (mPref.getString("service", "").matches("")) {
medit.putString("service", "service").commit();
Intent intent = new Intent(getApplicationContext(), GoogleService.class);
startService(intent);
} else {
Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show();
}
}
});
fn_permission();
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION
},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
latitude = Double.valueOf(intent.getStringExtra("latutide"));
longitude = Double.valueOf(intent.getStringExtra("longitude"));
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
tv_area.setText(addresses.get(0).getAdminArea());
tv_locality.setText(stateName);
tv_address.setText(countryName);
} catch (IOException e1) {
e1.printStackTrace();
}
tv_latitude.setText(latitude+"");
tv_longitude.setText(longitude+"");
tv_address.getText();
}
};
@Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, new IntentFilter(GoogleService.str_receiver));
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
Googleervice.java
package servicetutorial.service;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by deepshikha on 24/11/16.
*/
public class GoogleService extends Service implements LocationListener{
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
double latitude,longitude;
LocationManager locationManager;
Location location;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000;
public static String str_receiver = "servicetutorial.service.receiver";
Intent intent;
public GoogleService() {
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(),5,notify_interval);
intent = new Intent(str_receiver);
// fn_getlocation();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
private void fn_getlocation(){
locationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnable && !isNetworkEnable){
}else {
if (isNetworkEnable){
location = null;
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000,0,this);
if (locationManager!=null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location!=null){
Log.e("latitude",location.getLatitude()+"");
Log.e("longitude",location.getLongitude()+"");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
}
if (isGPSEnable){
location = null;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
if (locationManager!=null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location!=null){
Log.e("latitude",location.getLatitude()+"");
Log.e("longitude",location.getLongitude()+"");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
}
}
}
private class TimerTaskToGetLocation extends TimerTask{
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
fn_getlocation();
}
});
}
}
private void fn_update(Location location){
intent.putExtra("latutide",location.getLatitude()+"");
intent.putExtra("longitude",location.getLongitude()+"");
sendBroadcast(intent);
}
}
添加此依赖项
compile 'com.google.android.gms:play-services:9.4.0'
其余答案均未使用:
com.google.android.gms.location.FusedLocationProviderClient
这是融合定位提供商,也是谷歌与融合定位提供商互动的主要切入点,很难找到一个好的例子。这是谷歌于2017年年中发布的。
Google Play服务位置API优于Android框架位置API(Android.location)
如果您当前正在使用Android框架位置API,强烈建议您尽快切换到Google Play services位置API。
要使用Google Location API,请首先将其添加到构建中。渐变
compile 'com.google.android.gms:play-services:11.0.0'
然后您可以使用这个类Wherebouts。java
:
import android.location.Location;
import android.os.Looper;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
/**
* Uses Google Play API for obtaining device locations
* Created by alejandro.tkachuk
* alejandro@calculistik.com
* www.calculistik.com Mobile Development
*/
public class Wherebouts {
private static final Wherebouts instance = new Wherebouts();
private static final String TAG = Wherebouts.class.getSimpleName();
private FusedLocationProviderClient mFusedLocationClient;
private LocationCallback locationCallback;
private LocationRequest locationRequest;
private LocationSettingsRequest locationSettingsRequest;
private Workable<GPSPoint> workable;
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
private Wherebouts() {
this.locationRequest = new LocationRequest();
this.locationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
this.locationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
this.locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(this.locationRequest);
this.locationSettingsRequest = builder.build();
this.locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult); // why? this. is. retarded. Android.
Location currentLocation = locationResult.getLastLocation();
GPSPoint gpsPoint = new GPSPoint(currentLocation.getLatitude(), currentLocation.getLongitude());
Log.i(TAG, "Location Callback results: " + gpsPoint);
if (null != workable)
workable.work(gpsPoint);
}
};
this.mFusedLocationClient = LocationServices.getFusedLocationProviderClient(MainApplication.getAppContext());
this.mFusedLocationClient.requestLocationUpdates(this.locationRequest,
this.locationCallback, Looper.myLooper());
}
public static Wherebouts instance() {
return instance;
}
public void onChange(Workable<GPSPoint> workable) {
this.workable = workable;
}
public LocationSettingsRequest getLocationSettingsRequest() {
return this.locationSettingsRequest;
}
public void stop() {
Log.i(TAG, "stop() Stopping location tracking");
this.mFusedLocationClient.removeLocationUpdates(this.locationCallback);
}
}
通过传递一个Workable
对象,可以像这样使用活动。一个可工作的对象只不过是一个自定义的类似回调的对象。
Wherebouts.instance().onChange(workable);
通过使用像Workable这样的回调,您将在活动中编写与UI相关的代码,并将使用GPS的繁忙工作留给助手类,如Wherebouts。
new Workable<GPSPoint>() {
@Override
public void work(GPSPoint gpsPoint) {
// draw something in the UI with this new data
}
};
当然,您需要请求Android操作系统的相应权限才能使用您的应用程序。您可以阅读以下文档了解更多信息或进行一些研究。
问题内容: 干杯,我正在尝试通过Android获取当前的GPS位置。我也遵循了这篇教程和Vogellas的文章。虽然没有用。使用LocationManager.NETWORK_PROVIDER时,无论我站在哪里,我总能得到51的纬度和9的经度。当使用LocationManager.GPS_PROVIDER时,我什么也没得到。 虽然使用GMaps时一切正常::S不知道为什么。如何像GMaps一样获取
问题内容: 我正在尝试通过GPS功能获取用户的当前位置, 编写了一个实现的简单类 通过一个简单的动作,我正在访问这些经度和纬度值 但是它总是返回0.0作为结果。无法找出问题所在。 问题答案: 您必须在onCreate()返回之后才能触发您的位置更新回调。如果您将经纬度变量初始化为虚拟值,则可能会看到您正在打印这些值。 在onLocationChanged中添加一些日志记录,以便可以看到它已被触发,
问题内容: 关于基本的Android编程,我还有另一个问题: 如何访问GPS以获取正在运行该应用程序的手机的当前位置?检索信息需要多长时间?在这种情况下,GPS可能会被禁用,如何再次启用/禁用它。 必须在andorid清单中授予哪些权限? 问候和感谢您的回答, 诗丹 问题答案: 一些答案: 访问:请参见LocationManager和LocationListener。 权限:android.per
问题内容: 我正在尝试在android模拟器上使用gps,我有以下代码: 我在清单中添加了以下行: 并且我已经使用DDMS方法和geo fix方法设置了gps位置,但是当我运行代码时,我在Toast行上得到了一个NullPointerExeption,可能是因为loc为空。 我不知道错误在哪里…您能帮我吗? 更新! 感谢您的帮助,现在我使用以下代码,但没有收到任何错误,但是它不会在onChan
本文向大家介绍Android实现Service获取当前位置(GPS+基站)的方法,包括了Android实现Service获取当前位置(GPS+基站)的方法的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了Android实现Service获取当前位置(GPS+基站)的方法。分享给大家供大家参考。具体如下: 需求详情: 1)、Service中每隔1秒执行一次定位操作(GPS+基站) 2)、定位的
我需要检查控制器中的用户权限,以决定将哪个参数列表发送到视图。我知道我可以通过两种方式检查特定用户是否有特定的角色: < li >方法1 -使用以下代码创建helper类:securitycontextholder . get context()。getAuthentication()。getAuthorities()。流()。anyMatch(grantedAuthority - 但是哪种方式是