RequestLocationUpdates生命时间

时间:2016-03-10 21:22:13

标签: android locationmanager

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

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

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

2 个答案:

答案 0 :(得分:1)

我认为在大多数情况下,您需要注册BroadcastReceiver。您可以观看的其中一个广播是当位置发生变化时。这有一些后勤问题,例如如何与BroadcastReceiver交互以及应用程序将消耗多少电池。可以找到有关如何解决这些问题的详细摘要here

基本上你会想要制作一个Intent(你正在寻找你正在寻找的事件的特定方式)和一个PendingIntent(一种使该事件与LocationServices交互的方法)。

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

答案 1 :(得分:0)

最后,我找到的最佳解决方案是使用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是一个好主意,但是很费力,因为他们不允许在这个类中使用处理程序。无论如何,您需要该服务在后台运行。

相关问题