即使用户关闭屏幕或关闭应用程序(非强制停止),我也需要每10分钟检查一次当前用户位置。对于LocationCheckService的启动,我正在使用AlarmService,但它始终开始检查位置(例如onLocationChanged)。如何通过网络或GPS提供商每10分钟只发一次位置更新请求(每次没有onLocationChanged)?
MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, LocationCheckService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 100, 200, pendingIntent);
}
}
LocationCheckService.class
public class LocationCheckService extends Service {
LocationManager locationManager = null;
@SuppressLint("MissingPermission")
@Override
public void onCreate() {
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, new LocationListener(LocationManager.NETWORK_PROVIDER));
new Timer().schedule(new MyTimer(), 0, 10000);
}
@SuppressLint("MissingPermission")
class MyTimer extends TimerTask {
@SuppressLint("MissingPermission")
@Override
public void run() {
try {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> listAddress = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (listAddress != null && listAddress.size() > 0)
Log.d(TAG, listAddress.get(0).getCountryCode());
listAddress = geocoder.getFromLocation(1.3707295, 32.3032414, 1);
if (listAddress != null && listAddress.size() > 0)
Log.d(TAG, listAddress.get(0).getCountryCode());
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
@Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
}
@Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
@Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
}