【发布时间】: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 答案中完全解释,因此您需要缩小问题范围。