如何定期将我的当前位置发送到网络服务?
How can I send my current location to webservice periodically?
我想在后台定期将我当前的位置信息发送到数据库。例如;每 5 分钟一次。即使用户不在应用程序中,位置也必须在后台发送。最好的方法是什么?你能给我什么建议?
public class AlarmReceiver extends BroadcastReceiver {
private FusedLocationProviderClient client;
private Context context;
@Override
public void onReceive(Context context, Intent intent) {
this.context = context;
client = LocationServices.getFusedLocationProviderClient(context);
if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
client = LocationServices.getFusedLocationProviderClient(context);
client.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// You can send to your webservice in here.
Log.i("TEST_LOCATION", location.getLatitude()+"");
}
});
}
}
您应该在 Activity class 开始。
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), REQUEST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(), 5*60*1000, pendingIntent);
并且您应该在清单中添加。
<receiver android:name=".AlarmReceiver" />
您可以通过使用 Pendingintent 和 BroadcastReceiver 来实现。
我想在后台定期将我当前的位置信息发送到数据库。例如;每 5 分钟一次。即使用户不在应用程序中,位置也必须在后台发送。最好的方法是什么?你能给我什么建议?
public class AlarmReceiver extends BroadcastReceiver {
private FusedLocationProviderClient client;
private Context context;
@Override
public void onReceive(Context context, Intent intent) {
this.context = context;
client = LocationServices.getFusedLocationProviderClient(context);
if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
client = LocationServices.getFusedLocationProviderClient(context);
client.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// You can send to your webservice in here.
Log.i("TEST_LOCATION", location.getLatitude()+"");
}
});
}
}
您应该在 Activity class 开始。
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), REQUEST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(), 5*60*1000, pendingIntent);
并且您应该在清单中添加。
<receiver android:name=".AlarmReceiver" />
您可以通过使用 Pendingintent 和 BroadcastReceiver 来实现。