我终于找到了我的问题的答案。我们可以在后台运行许多方法,如 Intent Service 和 Alarm Manager。我使用了后台进程的警报管理器。它会每 5 分钟调用一次服务。在我的MainActivity 中,我输入了下面提到的代码。
private void scheduleNotify()
{
Intent notificationIntent = new Intent(this, SendLocation.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,0,1000*60*5,pendingIntent);
}
在AlarmManager,我设置了setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,0,1000*60*5,pendingIntent);
它将每 5 分钟重复一次持续时间(1000*60*5 毫秒 = 5 分钟)
SendLocation.class
public class SendLocation extends BroadcastReceiver implements LocationListener {
@Override
public void onReceive(Context mContext, Intent intent) {
try {
locationManager = (LocationManager) mContext.getSystemService(mContext.LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}catch (Exception e){
}
Log.i("sendlocation","Every 5 minutes it will appear in Log Console"+latitude+" "+longitude);
// code for send location to srver
}