我想将位置更新作为服务运行。现在我能够正确运行服务,但位置更新发生了两次,这是代码,
的AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<service
android:name=".services.LocationService"
android:icon="@drawable/ic_location"
android:label="Location Service">
<intent-filter>
<action android:name="android.service.notification.service" />
</intent-filter>
</service>
在Activity类中,我们使用startLocationService()
启动服务,stopLocationService()
停止服务,还创建了一个Broadcast Receiver来获取Activity Calss上的位置更新。
private BroadcastReceiver broadcastReceiver;
private Intent mLocationServiceIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigtaion_drawer);
AppController.getInstance().activityResumed();
broadcastReceiver = createBroadcastReceiver();
registerReceiver(broadcastReceiver, new IntentFilter(getPackageName()));
if (!Permissions.hasLocationPermission(this)) {
Permissions.requestLocationPermission(this, PermissionKeys.LOCATION_REQUEST_HOME_ON_RESUME);
} else
startLocationService();
}
private BroadcastReceiver createBroadcastReceiver() {
return new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra(LocationService.LOCATION_UPDATED)) {
Bundle b = intent.getExtras();
if (b != null) {
Location mCurrentLocation = (Location) b.get(LocationService.LOCATION_UPDATED);
}
}
}
};
}
//Function To Start the Service
public void startLocationService() {
if (mLocationServiceIntent == null)
mLocationServiceIntent = new Intent(this, LocationService.class);
startService(mLocationServiceIntent);
}
//Function To Stop the Service
public void stopLocationService() {
if (mLocationServiceIntent != null)
stopService(mLocationServiceIntent);
}
LocationService.java
public class LocationService extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
public static final String LOCATION_UPDATED = "LocationUpdated";
public static final String LATITUDE = "Latitude";
public static final String LONGITUDE = "Longitude";
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
private static final String TAG = "###LocationService:: ";
private static final int LOCATION_INTERVAL = 15000;
private static final int FASTEST_INTERVAL = 10000;
private static final float LOCATION_DISTANCE = 7f;
@Override
public void onCreate() {
if (isGooglePlayServicesAvailable()) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(LOCATION_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//mLocationRequest.setSmallestDisplacement(10.0f); /* min dist for location change, here it is 10 meter */
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
}
//Check Google play is available or not
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
return ConnectionResult.SUCCESS == status;
}
@Override
public void onConnected(Bundle bundle) {
Log.e(TAG, "Connected");
startLocationUpdates();
}
@Override
public void onConnectionSuspended(int i) {
Log.e(TAG, "Connection suspended");
}
protected void startLocationUpdates() {
Log.e(TAG, "Start Location Updates");
try {
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
} catch (IllegalStateException e) {
}
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.e(TAG, "Location Changed : " + location.getLatitude() + "," + location.getLongitude());
Intent intent = new Intent(getPackageName());
intent.putExtra(LOCATION_UPDATED, location);
sendBroadcast(intent);
}
}
/* LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};*/
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.e(TAG, "onConnectionFailed:: "+connectionResult.getErrorMessage());
}
}
答案 0 :(得分:1)
我已经通过在启动服务之前添加条件检查来修复此问题,
我更新的startLocationService()
功能就像,
//Function To Start the Service
public void startLocationService() {
if (mLocationServiceIntent == null)
mLocationServiceIntent = new Intent(this, LocationService.class);
if(!isServiceRunning(HomeScreenActivity.this, LocationService.class)) {
startService(mLocationServiceIntent);
}
}
这是检查服务是否已经运行的功能。
//This function is to check the service is already running or not
public boolean isServiceRunning(Context context, Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.e("ServiceRunning", serviceClass.getSimpleName() + " is alredy running");
return true;
}
}
return false;
}