【问题标题】:How can I send my current location to webservice periodically?如何定期将当前位置发送到网络服务?
【发布时间】:2019-07-24 13:18:09
【问题描述】:

我想在后台定期将我当前的位置信息发送到数据库。例如;每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 类中启动它。

    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" />

【问题讨论】:

  • 对于现代 Android 设备,您需要使用 ForegroundService 实现应用程序,并且用户需要手动将应用程序列入白名单以免除电池使用优化。该服务将请求和处理位置更新并将数据保存在本地或发送到您的后端。但这太宽泛了,无法在 StackOverflow 答案中完全解释,因此您需要缩小问题范围。

标签: android location


【解决方案1】:

您可以通过使用 Pending Intent 和 BroadcastReciever 来实现。

【讨论】:

  • 谢谢。这对我有帮助。
  • 很高兴知道@BarışSağlam 快乐编码:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多