RequestLocationUpdates 生命周期

RequestLocationUpdates Time of life

RequestLocationUpdates 是 LocationManager 的一个方法,定期接收 GPS 信息。

我认为如果我从 onCreate 应用程序发送应该不会有问题,因为它不会对主线程过度收费,对吗?

如果我想接收信息 requestLocationUpdates,即使在应用程序关闭后,我应该从哪里发送?

我认为在大多数情况下,您会想要注册一个 BroadcastReceiver. one of the broadcasts that you can watch for is when the location changes. There are a few logistical concerns with this such as how to interact with the BroadcastReceiver and how much battery your application will consume. A good summary of how to address these concerns can be found here

本质上,您需要创建一个 Intent(您识别正在寻找的事件的特定方式已经发生)和一个 PendingIntent(一种使该事件与 LocationServices 交互的方式)。

PendingIntent launchIntent = PendingIntent.getBroadcast(context, 0, myIntent, 0);
manager.requestLocationUpdates(provider, minTime, minDistance, launchIntent);

最后我找到的最好的解决方案是使用Service,如下:

public class GpsService extends Service implements LocationListener{

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    LocationManager LocManager =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    LocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, this);
    return Service.START_STICKY;
}

public void onLocationChanged(Location location) {
    Log.i("location", String.valueOf(location.getLongitude()));
    Log.i("location", String.valueOf(location.getLatitude()));
}

public void onProviderDisabled(String provider) {
    Log.i("info", "Provider OFF");
}

public void onProviderEnabled(String provider) {
    Log.i("info", "Provider ON");
}

public void onStatusChanged(String provider, int status, Bundle extras) {
    Log.i("LocAndroid", "Provider Status: " + status);
    Log.i("info", "Provider Status: " + status);
}

}

然后在 onCreate() 中启动服务:

public class PacienteApp extends Application {
@Override
public void onCreate() {
    Intent intent = new Intent(this, GpsService.class);
    this.startService(intent);
}
}

使用 Broadcast Receiver 是个好主意,但很费力,因为他们不允许在此 class 中使用处理程序。无论如何,您需要在后台为 运行 提供服务。